开发者

overriding previously-bound click events

开发者 https://www.devze.com 2022-12-29 05:33 出处:网络
When I use this code with an element whose id is \"foobar\": $(\"#foobar\").click(function () { alert(\"first\"); });

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号