javascript - 无法检测窗口是否已加载

标签 javascript html dom-events

我目前正在计算我的应用程序中打开的选项卡的数量。但我的问题是我的脚本似乎无法检测到事件加载。这是我的代码。 我正在使用 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/

相关文章:

html - 如何在 table 周围生成 flex 的边框?

javascript - 防止浏览器在 HTML5 History popstate 上滚动

javascript - 在 Javascript 中对输入字段进行分组

javascript - Rxjs 中不存在 Angular 6 throttleTime

html - 包装图像位于右侧 100% 高度不重绘

javascript - 如何在 Javascript 中将 UTC 时间转换为本地时间

jquery - 是否可以设置 DIV 标签,以免将下面的对象向下推?

JavaScript - OffFocus 事件?

javascript - 为什么没有非 Flash RTMP 视频播放器?或者有吗?

javascript - 使 jQuery ComboBox 的选项不可选择