jQuery 加载函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3623890/
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-26 15:46:09  来源:igfitidea点击:

jQuery onload function

jquery

提问by Shaun

I m using the following script to call a onload function but it does not works in IE

我正在使用以下脚本调用 onload 函数,但它在 IE 中不起作用

("#body").attr({onload : "calFact();"});

("#body").attr({onload : "calFact();"});

回答by gnarf

If you are using jQuery you could use the ready()function like so:

如果您使用的是 jQuery,则可以ready()像这样使用该函数:

$(function() {
  callFact();
});

or even more simply, just pass the method to jQuery:

或者更简单地说,只需将方法传递给 jQuery:

$(callFact);

That will fire as soon as the DOM is available to manipulate, sometimes earlier than onload.

一旦 DOM 可用于操作,它就会触发,有时早于onload.

回答by Tgr

You cannot set onload event handlers on anything other than the window. (Well, you can, but it will have no effect.) If you want calFactto run at the onload event, you should use $(window).load(calFact);. But generally it is more useful to call things at the DOMready event: $(document).ready(calFact);or just $(calFact);for short. The difference is that onload happens when everything loaded (including images, which are slow to load), and DOMready happens when the DOM tree is loaded (but images not necessarily yet).

您不能在窗口以外的任何地方设置 onload 事件处理程序。(好吧,你可以,但它不会有任何影响。)如果你想calFact在 onload 事件中运行,你应该使用$(window).load(calFact);. 但通常在 DOMready 事件中调用更有用:$(document).ready(calFact);或者$(calFact);简称。不同之处在于 onload 在所有内容加载时发生(包括加载缓慢的图像),而 DOMready 在 DOM 树加载时发生(但图像不一定尚未加载)。

Also, there is not much point in assigning an id of bodyto the body when there is only one of it anyway; you can just use $('body').

此外,body当身体只有一个时,为它分配一个 id 也没有多大意义;你可以使用$('body').

回答by Richard Neil Ilagan

You'll probably want to do this instead:

你可能想要这样做:

$('#body').ready(function(){
    calFact();
});

回答by Rahul

You should use ready()

你应该使用 ready()

More at http://api.jquery.com/ready/

更多信息请访问http://api.jquery.com/ready/