I would like to delegate the event one for the click. Does anyone know if it is possible to do it?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
I'm sure there is a neat way of doing it, but a simple way to do it would be something like this:
EDIT: Thanks to the comments below I decided to use data, now this doesn't screw the DOM all up for w3c standards.
I'm going to assume that you want the event to fire only once PER matched element rather than unbind entirely on the first click.
I'd implement it like so:
This will fire only once per element. Technically, it fires everytime but is flagged the first time it is clicked so the code will not execute again.
The inherent problem of simulating a .one() handler w/ delegate is that using .one() each element that was matched in the selector is bound its own event handler. So when it is fired for the first time it unbinds/removes the handler from that element. You can't do that with .delegate() because only a SINGLE handler is being used for ALL the matched elements.
While the code above simulates it perfectly, it is still somewhat hackish because it doesn't literally do the same thing that .one() does (unbinding an event handler).
Since this post is a few years old, I just wanted to provide a complete updated example for more contemporary readers (2015). The logic is no different from the other answers here, but jQuery's methods have evolved since 2011. Specifically: