开发者

How to check if the radio buttons has already bound with a "change" event handler

开发者 https://www.devze.com 2023-04-03 18:49 出处:网络
If I have radio buttons : <input id=\"y0\" type=\"radio\" name=\"myRadioBtns\" value=\"a\" checke开发者_如何学JAVAd> <label for=\"y0\"></label>

If I have radio buttons :

<input id="y0" type="radio" name="myRadioBtns" value="a" checke开发者_如何学JAVAd> <label for="y0"></label>
<input id="y1" type="radio" name="myRadioBtns" value="b">  <label for="y1"></label>
<input id="y2" type="radio" name="myRadioBtns" value="c">  <label for="y2"></label>

The radio buttons may have already bound a change event handler like following:

$('input[name='myRadioBtns']').change(function() {
  //EVENT HANDLER
});

I need to check if the radio buttons have already bound with a "change" event handler or not.

My question is How to check if the radio buttons has already bound with a "change" event handler?


If you want to test whether a change event has already been bound before you bind another one, use this:

var $el = $('input[name='myRadioBtns']');

if( ! ($el.data('events') && $el.data('events').change) ) {

   $el.change(function() {
       //EVENT HANDLER
   });
}


You can get bound events with:

.data('events')


Also, you can bind multiple namespaced change events that each do different things. For example if you were writing a jQuery plugin that needs to bind events to elements, but not remove any existing events that might already be set on the page.

Whenever I'm writing a jQuery plugin I make sure all events are bound like this:

    $(":checkbox").on("change.myNamespace", function(){
        //Do Stuff - this won't replace existing change events on checkboxes!
    });
0

精彩评论

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