Javascript jQuery 等价于 body onLoad
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4638296/
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
jQuery equivalent of body onLoad
提问by Joel
Is it allowed to use <body onLoad="myfunc()">
along with jQuery's document.ready()
handlers?
I can't find a way to achieve the same functionality of the <body onLoad>
with jQuery.
是否允许<body onLoad="myfunc()">
与 jQuery 的document.ready()
处理程序一起使用?我找不到一种方法来实现<body onLoad>
与 jQuery相同的功能。
An example of a use case would be a facebook application. An Iframe facebook app requires the use of the FB.Canvas.setSize
function which resize the iframe.
用例的一个示例是 Facebook 应用程序。iframe facebook 应用程序需要使用FB.Canvas.setSize
调整 iframe 大小的函数。
I would need to fire it up only when all elements on the page are finished loading.
只有当页面上的所有元素都完成加载时,我才需要启动它。
回答by Kevin
$(window).load(myfunc)
is what you're looking for. If you're working with the load event of an iframe, you can replace window
with the iframe element/selector.
$(window).load(myfunc)
就是你要找的。如果您正在处理 iframe 的加载事件,则可以替换window
为 iframe 元素/选择器。
回答by sgriffinusa
From the jQuery API on the readyhandler:
从就绪处理程序上的 jQuery API :
The .ready() method is generally incompatible with the <body onload=""> attribute. If load must be used, either do not use .ready() or use jQuery's .load() method to attach load event handlers to the window or to more specific items, like images.
.ready() 方法通常与 <body onload=""> 属性不兼容。如果必须使用 load,请不要使用 .ready() 或使用 jQuery 的 .load() 方法将加载事件处理程序附加到窗口或更具体的项目,如图像。
回答by putude
This works as well:
这也有效:
$(window).load(function(){
// ..
myfunc();
// ..
});
回答by ThatOneGuy
Found this thread updating some old code that had <body onload="someFunc()">
so to give an updated answer:
发现此线程更新了一些旧代码,<body onload="someFunc()">
因此必须提供更新的答案:
Don't use load()
. While $(document).ready(function(){...});
should work (depending on your use case) you actually want: $(window).on('load', function(){...});
to more closely mimic <body onload="...">
不要使用load()
. 虽然$(document).ready(function(){...});
应该工作(取决于你的用例)你真正想要的:$(window).on('load', function(){...});
更密切地模仿<body onload="...">
Some threadssuggest this has been deprecated since jQuery 1.8 (as well as .unload()
and .error()
) and should be replaced with proper .on()
implementations. I've confirmed that using load()
on 3.3.1 results in an error, namely: indexOf is not a function
in jquery.min.js
一些线程表明,自 jQuery 1.8(以及.unload()
和.error()
)以来,这已被弃用,应替换为适当的.on()
实现。我已经确认load()
在 3.3.1上使用会导致错误,即:indexOf is not a function
在 jquery.min.js 中
回答by Andrey
Try load()
:
尝试load()
:
jQuery(document).load(myfunc)