jQuery 使用 .one() API 只加载一次 javascript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27676497/
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
loading of javascript function only once using .one() API
提问by lukieleetronic
I have a questions about JQuery's .one() API, I'm trying to load some functions only once after the document has been fully loaded using .one() API and this doesn't seem to work and I can't figure out why...
我对 JQuery 的 .one() API 有疑问,我试图在使用 .one() API 完全加载文档后仅加载一些函数一次,但这似乎不起作用,我无法弄清楚为什么...
can I please get some help?
我可以帮忙吗?
$(document).one('load',function(){
// Perform something here...
});
回答by Naveen Kumar PG
This works use instead of "load" to "ready" not sure why its not working with the load
这可以使用而不是“加载”来“准备好”,不知道为什么它不能与负载一起工作
$(document).one('ready',function(){
// Perform something here...
alert("ther you go");
});
Keep in mind that "ready" fires before "load".
请记住,“就绪”在“加载”之前触发。
回答by Roko C. Buljan
Makes no sense to use .one()
in any of the combination document ready
or window load
.
是没有意义的使用.one()
在任何组合document ready
或window load
。
Attach a handler to an event for the elements. The handler is executed at most once per element per event type
将处理程序附加到元素的事件。每个事件类型的每个元素最多执行一次处理程序
you clearly don't expect the ready
or load
to trigger twice. Those run once per session so it's quite silly to use .one()
for this (artificial) events.
您显然不希望ready
orload
触发两次。这些每个会话运行一次,因此.one()
用于此(人工)事件非常愚蠢。
Also it's good to know that:
另外很高兴知道:
$(document).one("ready", function(){
console.log("DOCUMENT SILLY ONE READY");
});
$(function(){ // (DOM ready shorthand)
console.log("DOCUMENT READY"); // not only will this one run...
});
// but also this is the order result:
// DOCUMENT READY
// DOCUMENT SILLY ONE READY
so to conclude, you only need
所以总而言之,你只需要
$(function(){
// DOM is ready to be manipulated
foo();
bar();
});
or:
或者:
$(window).load(function(){
// DOM, metadata, scripts, files, styles, images...etc are load and ready
foo();
bar();
});
and your functions will not run more than once.
并且您的函数不会多次运行。