I am trying to toggle a click event on and off to prevent multiple function calls. Below is my code. The click is turning off but I can't seem to turn it on again. Thoughts?
$("#element").click(function(){
doit();
$(this).off('click');
})
function doit(){
do stuff...
//turn click back on
$("#element").on('click');
}
You need to pass the handler back to the on method, also use .one() as you want to fire it only once
function clickHandler() {
doit();
}
$("#element").one('click', function () {})
function doit() {
//do stuff...
//turn click back on
$("#element").one('click', clickHandler);
}
You seem to have set the button off after calling doit() which turns it on. Try:
$("#element").click(function(){
$(this).off('click');
doit();
})
function doit(){
do stuff...
//turn click back on
$("#element").on('click');
}
Calling $("#element").on('click');
without providing the action handler is useless. You need to pass the handler again to turn it on.
$("#element").on('click', clickEvent);
function doit() {
// do stuff...
//turn click back on
$("#element").on('click', clickEvent);
}
function clickEvent() {
doit();
$("#element").off('click');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.