简体   繁体   中英

Jquery execute function only once

I have code:

$(Page).on('click', '*', function(e)
{
    myFunction();
}

function myFunction(){//do something...}

I would like the code in the function to be done only once, now when I click, for example, 5 times, the code from the function myFunction() will be executed 5 times. I don't want to change on('click', '*', ...

Use jQuery's one method.

Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

Simply change your .on to .one .

$(Page).one('click', '*', function(e) {
  myFunction();
});

function myFunction() {
  // do something
}

Here's the documentation for one

You can use the function $.one

$(Page).one('click', '*', function(e)
     myFunction();
});

Or, better:

$(Page).one('click', '*', myFunction);

Be careful with that event delegation who will bind the event click to the whole set of elements within the DOM tree of Page .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM