【问题标题】:How to check if the radio buttons has already bound with a "change" event handler如何检查单选按钮是否已与“更改”事件处理程序绑定
【发布时间】:2011-11-12 03:59:23
【问题描述】:

如果我有单选按钮:

<input id="y0" type="radio" name="myRadioBtns" value="a" checked> <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>

单选按钮可能已经绑定了一个更改事件处理程序,如下所示:

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

我需要检查单选按钮是否已经与“更改”事件处理程序绑定。

我的问题是如何检查单选按钮是否已经与“更改”事件处理程序绑定

【问题讨论】:

标签: javascript jquery jquery-selectors jquery-validate jquery-events


【解决方案1】:

您可以通过以下方式获取绑定事件:

.data('events')

【讨论】:

【解决方案2】:

如果你想在绑定另一个事件之前测试一个更改事件是否已经被绑定,使用这个:

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

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

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

【讨论】:

【解决方案3】:

此外,您可以绑定多个命名空间更改事件,每个事件执行不同的操作。例如,如果您正在编写一个 jQuery 插件,该插件需要将事件绑定到元素,但不删除页面上可能已经设置的任何现有事件。

每当我编写 jQuery 插件时,我都会确保所有事件都像这样绑定:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 2023-02-03
    • 2019-02-22
    • 2017-02-17
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    相关资源
    最近更新 更多