javascript 如何让javascript函数在dom准备好时只执行一次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7354839/
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
How to get a javascript function to execute only once on dom ready
提问by Linda
I'm getting alerted "hi" over and over again, how do I get it to do it once and stop:
我一遍又一遍地收到“嗨”的警报,我如何让它做一次并停止:
function doSomething() {
alert('hi');
}
$(function() {
doSomething();
});
回答by iOSAndroidWindowsMobileAppsDev
// Fired once when document is ready
$(document).one('ready', function () {
doSomething();
});
Using .one ensures this is done only once and not repeatedly.It is okay to put several document.ready event listeners (if you need other events to execute multiple times) as long as you do not overdo it, for the sake of readability.
使用 .one 确保只执行一次而不是重复。为了可读性,可以放置多个 document.ready 事件侦听器(如果您需要多次执行其他事件),只要不要过度。
.one is especially useful when you want the alert to appear the first time a web page is opened or when a mobile application is installed the first time.
当您希望在第一次打开网页或第一次安装移动应用程序时出现警报时,.one 尤其有用。
回答by romaninsh
I think you include your JS file multiple times from the HTML. Clean up your HTML.
我认为您从 HTML 中多次包含您的 JS 文件。清理你的 HTML。
Using:
使用:
$(function(){
});
is perfectly normal. Using more verbose form have no benefit. If you are writing a plugin, you might want to do this:
完全正常。使用更详细的形式没有任何好处。如果您正在编写插件,您可能需要这样做:
function($){
// $ always refers to jQuery here
...
}(jQuery);
// $ might not be defined here in compatibility mode.
回答by spam filter
The best way is ... with using cookie - like this:
最好的方法是......使用cookie - 像这样:
$(document).ready(function () {
if ($.cookie("blocker") == 1) {
//your code or without code;
return;
} else {
//your code for first time
$.cookie("blocker", 1, {
expires: 1 / 24 / 60 //time, this is one minut
});
}
});
This code is good if you have smarty on your page
如果您的页面上有 smarty,则此代码很好
回答by realshadow
Try with:
尝试:
window.onload = function() {
doSomething();
}
回答by James Johnson
Are you looking to do something like this?:
你想做这样的事情吗?:
$(document).ready(function() {
doSomething();
});
回答by Sam Dutton
You might want to stick to the more verbose style:
你可能想坚持更详细的风格:
function doSomething() {
alert('hi');
}
$(document).ready(function() {
doSomething();
});
回答by Jason Lewis
Raul is right, it would help to have the code...
劳尔是对的,拥有代码会有所帮助......
But based on my experience with this, what you want is something more along the lines of:
但根据我在这方面的经验,你想要的是更多的东西:
var doSomething = function() {
alert('hi');
}
$(document).ready(function () {
doSomething();
});