2014-05-16 36 views
0

我已經爲Windows 8編寫了一個WinJS應用程序(Metro-App)。問題是,只要我試圖訪問DOM(HTML)元素,就會得到「nullpointer異常」一個div。 問題的代碼是這樣的:WinJS DOM- Loading

WinJS.UI.Pages.define("/pages/home/home.html", { 
    ready: function (element, options) { 
     document.getElementById("inhalt").innerHTML = "test"; // causes NullpointerException 
    } 
}); 

但是當我這樣做,而不是,是沒有問題的。但我不想每次等待3秒鐘。

WinJS.UI.Pages.define("/pages/home/home.html", { 
    ready: function (element, options) { 
     window.setTimeout(function() { document.getElementById("inhalt").innerHTML = "test"; }, 3000); 
    } 
}); 

爲什麼拋出NullPointerException,我該如何解決它?

回答

1

這可能是因爲ready()是在頁面進入DOM之前調用的,所以document.getElementById找不到它。您正在通過就緒功能中的根元素,因此您可以改爲:

element.querySelector('#inhalt').innerHTML = "test"; 

而且應該有效。這是頁面儘可能不在頁面內使用ID的最佳做法,因此只需將其更改爲類class="inhalt"並將其設置爲element.querySelector('.inhalt')即可。