jQuery 移动单选按钮更改事件即使已选中也始终会触发

标签 jquery jquery-mobile event-handling radio-button onchange

我使用包含两个单选按钮的单选按钮组来根据选中的单选按钮动态更改页面内容。当所选单选按钮更改时,应更新内容。因此,我向单选按钮添加了一个事件处理程序。

html:

<fieldset data-role="controlgroup" data-type="horizontal" style="text-align: center" >
    <input name="radio" id="radio-a" type="radio" >
    <label for="radio-a">a → b</label>
    <input name="radio" id="radio-b" type="radio">
    <label for="radio-b">b → a</label>
</fieldset>

jQuery:

$(document).ready(function() {
    $(":input[name= 'radio']").on('change', function(){
        alert("DO SOMETHING");
    });
});

如果我使用一些没有 jQuery mobile 的单选按钮,一切都会按预期工作。仅当我选择未选中的单选按钮时才会触发更改事件。如果我单击已选中的单选按钮,则不会发生任何事情。

请参阅此 jsfiddle 进行演示: https://jsfiddle.net/6cnLgonk/21/

如果我现在包含 jQuery mobile 的 jscss,则更改事件始终会触发,无论单选按钮是否已选中: https://jsfiddle.net/6cnLgonk/19/ 请注意,代码是完全相同的,我只是链接了 jQuery mobile 文件以使单选按钮自动获取样式。

所需的行为是仅在尚未选中单选按钮时触发更改事件。我如何使用 jQuery 移动风格的单选按钮来完成此操作?

jQuery mobile js 是否以某种方式覆盖更改事件?我是否必须以某种方式手动设置检查单选按钮?感谢您的回答。

最佳答案

jQuery Mobile 实际上用标签 dom 元素替换了单选输入,并将单击处理程序添加到这些标签,然后触发底层单选按钮上的更改事件。

您可以向每个单选按钮添加值属性:

<fieldset data-role="controlgroup" data-type="horizontal" style="text-align: center" >
    <input name="radio" id="radio-a" type="radio" value="a" />
    <label for="radio-a">a → b</label>
        <input name="radio" id="radio-b" type="radio" value="b" />
    <label for="radio-b">b → a</label>
</fieldset>

然后您可以保存当前选择并进行检查:

var CurrentSelection;
$(document).ready(function() {
    $(":input[name= 'radio']").on('change', function(){
        var clicked = $(this).val();
        if (clicked != CurrentSelection){
            CurrentSelection = clicked;
            alert("DO SOMETHING");
        }
    });
});

Updated FIDDLE

关于jQuery 移动单选按钮更改事件即使已选中也始终会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30896576/

相关文章:

javascript - 如何通过 bootstrap 中的 selectpicker 插件使用 id 设置选定值

javascript - 如何将 radio 元件注入(inject)面板?

event-handling - JavaFX 2 文本区域 : How to stop it from consuming [Enter] and [Tab]

reactjs - 以处理事件为例

.net - 如何允许在事件处理程序连接到 COM 对象的对象上进行垃圾回收

jquery - 使用 Bootstrap 将两个 div 水平居中连续

javascript - 如何将 onclick 事件添加到表列?

php - HTML5 内容可编辑

javascript - 使用 JSON 新闻 api 创建搜索查询

jquery-mobile - pageinit 上的 jQuery 移动弹出窗口