我目前正在计算我的应用程序中打开的选项卡的数量。但我的问题是我的脚本似乎无法检测到事件加载。这是我的代码。 我正在使用 HTML5 网络存储和 native js。我使用 jQuery 不是为了了解更多有关原生 js 的信息。
(function(w) {
function Tabz(win, key) {
this.name = '';
this.storageKey = key;
if(win.name != '')
this.name = win.name;
else {
var windowArr = JSON.parse(localStorage.getItem(key)) || [];
this.name = "tabz_"+ windowArr.length;
win.name = this.name;
windowArr.push(this.name);
localStorage.setItem(this.storageKey, JSON.stringify(windowArr) );
}
}
Tabz.prototype.getStorage = function() {
return localStorage.getItem(this.storageKey);
}
Tabz.prototype.removeWindow = function() {
//remove window function here
}
var newWindow = new Tabz(w, 'counter');
window.load = function() {
var count = JSON.parse(newWindow.getStorage()).length;
alert(count!); // this wont execute so that I can check the count.
}
})(window);
最佳答案
您的问题在这一行:
window.load = function() {
这将向窗口添加一个load
属性,而不是添加一个事件监听器。我认为您正在寻找 onload
。
window.onload = function() {
顺便说一句,使用事件属性被认为是不好的做法。使用 addEventListener会更好。
window.addEventListener("load", function(){
//Do stuff...
});
关于javascript - 无法检测窗口是否已加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26499641/