I'm getting alerted "hi" ove开发者_JAVA百科r and over again, how do I get it to do it once and stop:
function doSomething() {
alert('hi');
}
$(function() {
doSomething();
});
// 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 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.
I think you include your JS file multiple times from the HTML. Clean up your 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.
Try with:
window.onload = function() {
doSomething();
}
Are you looking to do something like this?:
$(document).ready(function() {
doSomething();
});
The best way is ... with using cookie - like this:
$(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
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();
});
You might want to stick to the more verbose style:
function doSomething() {
alert('hi');
}
$(document).ready(function() {
doSomething();
});
精彩评论