简体   繁体   English

当还使用了preventDefault时,单选按钮的选中属性未设置

[英]radio button checked property not setting when preventDefault is also used

The problem I am having is that the radio buttons in my scenario are not being selected when they are clicked. 我遇到的问题是单击脚本时未选中我的方案中的单选按钮。 I have created a JSFiddle to show the code and the issue. 我创建了一个JSFiddle来显示代码和问题。

For whatever reason, I have an entire area that is surrounded in an element. 无论出于什么原因,我都有一个元素包围的整个区域。

<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>

There is a small section within this tag that needs to be protected from the default behaviour of the link. 此标记中有一小部分需要保护,以防止链接的默认行为。 This section contains some radio inputs which need to be selectable. 本节包含一些需要选择的无线电输入。

The way I currently have it, I am protecting the "protected" section with an event listener and: 目前,我使用事件监听器来保护“ protected”部分,并且:

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

I also have an event listener on the radio buttons so that I can perform the change of property when they are clicked. 我还在单选按钮上有一个事件侦听器,以便单击它们时可以执行属性更改。

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

Unfortunately, this is setting the checked attribute in the dom however the radio button is not being filled in on the screen for the user. 不幸的是,这是在dom中设置了选中的属性,但是用户没有在屏幕上填写单选按钮。

Any help would be greatly appreciated. 任何帮助将不胜感激。

You need to add stopPropagation() 您需要添加stopPropagation()

$('.protected > :radio').off('click').on('click', function (e) {
    e.stopPropagation();

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

Also, make sure to comment out 另外,请务必注释掉

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

You don't need them as the browser handles this for you. 您不需要它们,因为浏览器会为您处理。

DEMO 演示

What was happening is, since you had preventDefault in the container click handler, the nested click event was propagating to that click handler and was preventing the radio button from being set. 发生的事情是,由于容器单击处理程序中包含了preventDefault ,因此嵌套的click事件正在传播到该单击处理程序,并且阻止了单选按钮的设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM