开发者

Binding multiple events in jQuery

开发者 https://www.devze.com 2022-12-27 01:56 出处:网络
I have a custom jQuery plugin which binds a change event to a form element, in this case some input elements. The change event is used to indicate to some other components that a change has taken plac

I have a custom jQuery plugin which binds a change event to a form element, in this case some input elements. The change event is used to indicate to some other components that a change has taken place.

This works as it should.

However, I've come across the 开发者_如何学Goneed to bind an additional change event to the same input elements -- so that additional components can act on the event. I don't wish to replace the plugin's change, simply run an additional function afterwards.

Is there any way to bind multiple events in jQuery, or, what is the best method for accomplishing this?


You can bind multiple handlers for the same event. Bind the second change as you normally would:

​<input type="text" id="a" />​​​​​​​​​​​​​​​

​$("#a"​).change(function() { alert("1"); });
$("#a").change(function() { alert("2"); });​

$("#a").change(); // alerts 1, then 2


Events stack in jQuery. If you do:

<input type="button" value="Press me">

and:

$(":button").click(function() {
  alert("click");
}).click(function() {
  alert("click 2");
});

both will fire. So just bind another event to the relevant elements. It won't overwrite the first.

0

精彩评论

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