overriding previously-bound click events
When I use this code with an element whose id is "foobar":
$("#foobar").click(function () { alert("first"); });
$("#foobar").click(function () { alert("second"); });
I get two ale开发者_如何学运维rts: "first" and "second" second.
How do I specify a click event that also clears out any previous click events attached to the element? I want the last $("#foobar").click(...)
to erase any previously bound events.
You can unbind the events already attached to that element, and then attach the second event handler, so it will be the only one (note the unbind method).
$("#foobar").unbind("click").click(function() { alert("second"); });
$("#foobar").click(function () { alert("first"); });
$("#foobar").unbind('click').click(function () { alert("second"); });
Notice the unbind() method. It does exactly what it sounds like.
精彩评论