jQuery 中的 window.onload

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9095771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:19:54  来源:igfitidea点击:

window.onload in jQuery

jquery

提问by Rain

I have use the example of sizzle and there I got window.onload in the last of the code.

我使用了 sizzle 的例子,在最后一段代码中我得到了 window.onload 。

What does this means.

这是什么意思。

My code is like this:

我的代码是这样的:

var init = function () {
    var trail = Sizzle;
    var foo = trail('.foo');
    foo[0].onmouseover = function () {
        this.style.backgroundColor = (this.style.backgroundColor.indexOf('blue') === 0) ? 'yellow' : 'blue';
    };
    foo[1].onmouseover = function () {
        this.style.backgroundColor = (this.style.backgroundColor.indexOf('red') === 0) ? 'yellow' : 'red';
        jQuery(foo[1]).after("<b>Hello</b>");
    }
    foo[2].onmouseover = function () {
        this.style.backgroundColor = (this.style.backgroundColor.indexOf('green') === 0) ? 'yellow' : 'green';
        jQuery(foo[3]).toggle("slow");
        jQuery('b').remove();
    }
};
window.onload = init;

What does this mean?

这是什么意思?

回答by Guffa

It means that you are setting the initfunction to handle the onloadevent of the document. The initfunction will be called when all the content in the page has loaded.

这意味着您正在设置init函数来处理onload文档的事件。init当页面中的所有内容都已加载时,将调用该函数。

As you are using jQuery, you should use the jQuery events instead. The DOM events can only have one handler (unless you write code to chain the handlers), but the jQuery events can have multiple handlers:

当您使用 jQuery 时,您应该改用 jQuery 事件。DOM 事件只能有一个处理程序(除非您编写代码来链接处理程序),但 jQuery 事件可以有多个处理程序:

$(document).load(init);

If you have more than one script in the page that uses the onloadevent, one will replace the other. Even if you use jQuery events, a script that hooks up the DOM event will take over the jQuery event handler, like in this question. Using the jQuery event in all scripts solves that.

如果在使用该onload事件的页面中有多个脚本,一个将替换另一个。即使您使用 jQuery 事件,连接 DOM 事件的脚本也会接管 jQuery 事件处理程序,就像在这个问题中一样。在所有脚本中使用 jQuery 事件可以解决这个问题。

回答by defau1t

This means that on the load of window the function initwill be executed.

这意味着在窗口加载时function init将执行。