简体   繁体   中英

How to unbind and rebind an event based on selector change

This is more a learning piece for me around how event listeners bound to jquery selectors are handled.

so say i have the following code:

<html>
<div class = "one">one</div>
<div class = "two">two</div>
</html>

<script>
$(".one").click(function() {
$(this).removeClass("one").addClass("two");
console.log("one");
})
$(".two").click(function() {
console.log("two");
})

</script>

On the first click of one, the selector is no longer valid (as the class is now two instead of one). However the event is still bound to this element. This element will also not fire the ".two" handler as this has already been bound.

What would be the easiest way to unbind a handler with the initial click and then rebind afterwards?

Bind the events on the document , no need to unbind and rebind the events.

 $(document).on("click", ".one", function() { $(this).removeClass("one").addClass("two"); console.log("one"); }); $(document).on("click", ".two", function() { console.log("two"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="one">one</div> <div class="two">two</div> 

$(".one").unbind("click");
$(".one").bind("click", fn);

You can use unbind() to remove an event added with bind() (or binded like above)

https://jsfiddle.net/7yn7apte/ No re-binding

https://jsfiddle.net/7yn7apte/1/ Re-binding

Well, this answer your question. But, you'd better use on() and off() as bind() calls on() and unbind() calls off() .

You can find a more exhaustive explanation here https://stackoverflow.com/a/9113835/6341631

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