javascript - 如何检测单选按钮取消选择事件?

标签 javascript jquery

有没有一种简单的方法可以在单选按钮上附加“取消选择”事件?似乎只有在选择按钮时才会触发 change 事件。

HTML

<input type="radio" id="one" name="a" />
<input type="radio" id="two" name="a" />

JavaScript

$('#one').change(function() {
    if(this.checked) {
        // do something when selected
    } else { // THIS WILL NEVER HAPPEN
        // do something when deselected
    }
});​

jsFiddle

最佳答案

为什么不简单地创建一个自定义事件,比如说 deselect并让它触发被点击的 radio 组的所有成员,除了被点击的元素本身?以这种方式使用 jQuery 提供的事件处理 API 会更容易。

HTML

<!-- First group of radio buttons -->
<label for="btn_red">Red:</label><input id="btn_red" type="radio" name="radio_btn" />
<label for="btn_blue">Blue:</label><input id="btn_blue"  type="radio" name="radio_btn" />
<label for="btn_yellow">Yellow:</label><input id="btn_yellow" type="radio" name="radio_btn" />
<label for="btn_pink">Pink:</label><input id="btn_pink"  type="radio" name="radio_btn" />
<hr />
<!-- Second group of radio buttons -->
<label for="btn_red_group2">Red 2:</label><input id="btn_red_group2" type="radio" name="radio_btn_group2" />
<label for="btn_blue_group2">Blue 2:</label><input id="btn_blue_group2"  type="radio" name="radio_btn_group2" />
<label for="btn_yellow_group2">Yellow 2:</label><input id="btn_yellow_group2" type="radio" name="radio_btn_group2" />
<label for="btn_pink_group2">Pink 2:</label><input id="btn_pink_group2"  type="radio" name="radio_btn_group2" />

jQuery

// Attaching click event handlers to all radio buttons...
$('input[type="radio"]').bind('click', function(){
    // Processing only those that match the name attribute of the currently clicked button...
    $('input[name="' + $(this).attr('name') + '"]').not($(this)).trigger('deselect'); // Every member of the current radio group except the clicked one...
});

$('input[type="radio"]').bind('deselect', function(){
    console.log($(this));
})

取消选择事件只会在同一单选组的成员(具有相同 name 属性的元素)之间触发。

jsFiddle solution

编辑:为了考虑附加标签的所有可能位置(包装 radio 元素或通过 id 选择器附加),使用 onchange 可能更好。事件触发处理程序。感谢Faust指出这一点。

$('input[type="radio"]').on('change', function(){
    // ...
}

关于javascript - 如何检测单选按钮取消选择事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11173685/

相关文章:

javascript - 通过正则表达式拆分是重复参数 NodeJs

javascript - 数组中的 jquery 对象未定义

javascript - 将 json 数据连接到 html 页面

javascript - 函数在变量定义之前返回

jQuery 事件 - 忽略对点击的关注

javascript - 在 JS 中用不同的数组替换对象数组

jquery - 禁用空父项的列表项

javascript - 我如何使用 html a 标签来更改 div 的宽度和高度?

javascript - 选择所有有类(class)的家长

javascript - 用户点击提交按钮后,如何使图像或图标显示在另一个图像上?