已选中单选按钮 属性 未在还使用 preventDefault 时设置

radio button checked property not setting when preventDefault is also used

我遇到的问题是我的方案中的单选按钮在单击时未被选中。我创建了一个 JSFiddle 来显示代码和问题。

无论出于何种原因,我都有一个元素包围的整个区域。

<a href="/link">
    //some stuff
    <div class="protected">
        <input type="radio" name="b1" value="1" /> Button 1
        <input type="radio" name="b1" value="2" /> Button 2
    </div>
    //some stuff
</a>

此标记中有一小部分需要受到保护,不受 link 的默认行为的影响。此部分包含一些需要选择的无线电输入。

按照我目前的方式,我正在使用事件侦听器保护 "protected" 部分,并且:

$('.protected').off('click').on('click', function (e) {
    e.preventDefault();
});

我在单选按钮上也有一个事件侦听器,这样我就可以在单击它们时执行 属性 的更改。

$('.protected > :radio').off('click').on('click', function (e) {
    $(this).siblings(':radio').removeAttr('checked');
    $(this).attr('checked', 'checked');
});

不幸的是,这是在 dom 中设置 checked 属性,但是没有为用户在屏幕上填写单选按钮。

如有任何帮助,我们将不胜感激。

您需要添加stopPropagation()

$('.protected > :radio').off('click').on('click', function (e) {
    e.stopPropagation();
    
    //$(this).siblings(':radio').removeAttr('checked');
    //$(this).attr('checked', 'checked');
});

另外,一定要注释掉

$(this).siblings(':radio').removeAttr('checked');
$(this).attr('checked', 'checked');

您不需要它们,因为浏览器会为您处理。

DEMO

发生的事情是,由于您在容器点击处理程序中有 preventDefault,嵌套的点击事件传播到该点击处理程序并阻止设置单选按钮。