Allow onclick just once
-
08-10-2019 - |
سؤال
In order to add a very long list of option elements to a select list I add them on-click. I want to prevent that the list is added multiple times. How can I do that?
$("#skiresort").click(function(){
$("#skiresort").load("/v3/inc/review.php");
});
المحلول
There is a method for executing an event handler only once: .one()
:
$("#skiresort").one('click', function(){
$("#skiresort").load("/v3/inc/review.php");
});
نصائح أخرى
Felix answer is perfect for jQuery, I'm adding this just to show a generic JavaScript technique for it:
function runOnce(f) {
var called = false;
return function() {
if (!called) {
called = true;
return f.apply(this, arguments);
}
};
}
Now you can use it like this:
var myNewFunction = runOnce(myFunction); // this does not run "myFunction", but returns a new one that will only run once.
myNewFunction(1, 2, 3); // runs the "myFunction" and returns whatever it returns
myNewFunction(1, 2, 3); // doesn't do anything, just returns undefined
لا تنتمي إلى StackOverflow