2012-09-30 64 views
0

的default.html和外面我有default.html中內的下列頁面元素:的Win8:訪問頁面元素default.js

<div id ="content"> 
    <div id="output"></div> 
</div> 

並在default.js:

...  
args.setPromise(WinJS.UI.processAll().done(function() 
{ 
    var theOutput = document.getElementById("output"); 
    theOutput.innerText = "This is the output"; 
})); 
.... 

這成功地產生了只有文本「這是輸出」的應用程序

但是如果我移動到這個新的腳本的script.js:

(function() 
{ 
    "use strict"; 

    var theOutput = document.getElementById("output"); 
    theOutput.innerText = "This is the output"; 
}()); 

而且添加的script.js在default.html中的腳本參考:

<script src="/js/script.js"></script><script src="/js/script.js"></script> 

我得到的錯誤

JavaScript runtime error: Unable to set property 'innerText' of undefined or null reference

如何在default.js之外的其他腳本中訪問輸出div?

回答

0

事實證明,script.js需要等到頁面元素完全處理完畢。下面的代碼運行的罰款:

(function() 
{ 
    "use strict"; 
    WinJS.Utilities.ready(function() 
    { 
    var theOutput = document.getElementById("output"); 
    theOutput.innerText = "This is the output"; 
    }); 
}()); 
+0

您可以使用相同的樣板'WinJS.UI.processAll( )'代碼,它也應該工作。 – kamranicus

0

您也可以處理DOMContentLoaded事件一旦DOM已經建成(儘管圖像可能有尚未完全加載),這觸發了。這就是我在很多基於Windows畫布的Windows Store遊戲中所做的。

這個添加到主功能:

document.addEventListener("DOMContentLoaded", initialize, false); 

然後,只需你想在初始化到斷火代碼:

function initialize() { 
    //Init Canvas 
    canvas = document.getElementById("canvas"); 
    ctx = canvas.getContext("2d");