简体   繁体   English

dom加载后的Javascript调用方法

[英]Javascript call method after dom has loaded

At the moment the id method in this object will alert undefined as it is called before the document has loaded. 目前,此对象中的id方法将发出未定义的警报,因为它在文档加载之前被调用。 I have a method for checking if the dom has loaded but am stuck on how to get that method to trigger the id method when the dom has loaded. 我有一个方法来检查dom是否已加载,但是在如何加载dom时仍无法获取该方法来触发id方法。

I can't simply add a call to the id method in the dom loaded method as it will be used for other unrelated tasks. 我不能简单地在dom加载方法中添加对id方法的调用,因为它将用于其他不相关的任务。

function myHandler(sel) {
    function myObject(sel) {
        this.sel = sel;
        myObject.prototype.init = function () {
            this.ready();
        }
        myObject.prototype.id = function () {
            alert(document.getElementById(this.sel).id);
        }
        myObject.prototype.ready = function () {
            document.onreadystatechange = function () {
                var state = document.readyState
                if (state == 'interactive') {} else if (state == 'complete') {}
            }
        }
    }
    return newTask = new myObject(sel);
    newTask.init;
}
myHandler('element').id();

Here is a rewritten version of your code: 这是代码的重写版本:

var MyObject = function MyObject(selector) {
    this.selector = selector;

    this.init();
};

MyObject.prototype.alertId = function alertId() {
    alert(this.selector);
};

MyObject.prototype.init = function init() {
    var that = this;

    // are we there already?
    if (document.readyState == "interactive" ||
        document.readyState == "complete") {

        // yes, fire immediately
        this.alertId();
    } else {

        // no, wait until the DOM is parsed
        document.addEventListener("DOMContentLoaded", function(event) {
            that.alertId();
        });
    }
};

var my_object = new MyObject('foo');

Let's go through this: 让我们来看一下:

var MyObject = function MyObject(selector) {
    this.selector = selector;

    this.init();
};

This is the constructor for MyObject objects. 这是MyObject对象的构造函数。 As a convention, constructor functions are generally capitalized in Javascript, so I have renamed it. 按照惯例,构造函数通常以Javascript大写,因此我将其重命名。

In the constructor, we set up all the properties that are unique to each copy of MyObject you create by calling new MyObject('selector string') . 在构造函数中,我们通过调用new MyObject('selector string')您创建的MyObject每个副本所独有的所有属性。 In this case, it's just the selector we get as the argument. 在这种情况下,它只是我们作为参数获得的selector After that, we call init() on it on our new object. 之后,我们在新对象上调用init()

Every MyObject you create does not need its own init() and alertId() - it behaves the same for every copy. 您创建的每个MyObject都不需要自己的init()alertId() -每个副本的行为都相同。 So in order not to waste memory, we create it on the prototype which all MyObjects share: 因此,为了不浪费内存,我们在所有MyObjects共享的原型上创建它:

MyObject.prototype.alertId = function alertId() {
    alert(this.selector);
};

We could be certain that our selector is already available if you would include this script as the very last element at the bottom of your page, right before the closing tag. 如果您可以将此脚本作为页面底部的最后一个元素(紧接在结束标记之前),则可以确定选择器已经可用。 But a more robust way is to check: 但是更可靠的方法是检查:

MyObject.prototype.init = function init() {
    var that = this;

    // are we there already?
    if (document.readyState == "interactive" ||
        document.readyState == "complete") {

        // yes, fire immediately
        this.alertId();
    } else {

        // no, wait until the DOM is parsed
        document.addEventListener("DOMContentLoaded", function(event) {
            that.alertId();
        });
    }
};

If our DOM is already available to us, we execute alertId() immediately. 如果我们的DOM已经可用,我们将立即执行alertId() If not, we wait until it is by registering a callback for the DOMContentLoaded event. 如果不是,我们通过注册DOMContentLoaded事件的回调来等到它。

Note that I used that.alertId() in the callback, not this.alertId() . 请注意,我在回调中使用了that.alertId() ,而不是this.alertId() This is because when our callback function is executed, this will be the window context, not our current MyObject object. 这是因为在执行我们的回调函数的时候, this将是window背景下,不是我们当前MyObject对象。

To get around this, I saved our current this pointing to our object in the variable that . 为了解决这个问题,我将当前this指向对象的对象保存在变量that that remains available inside our callback function because Javascript has closures . 由于Javascript具有闭包,因此在回调函数that仍然可用。

Please note that the above code only works for modern browsers. 请注意,以上代码仅适用于现代浏览器。 If you need compatibility with Internet Explorer 8 and older, you will need to workaround its missing support for DOMContentLoaded with something like ContentLoaded . 如果需要与Internet Explorer 8及更早版本的兼容性,则需要使用ContentLoaded之类的方法来解决其对DOMContentLoaded缺少支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM