繁体   English   中英

单击父级时更改单选按钮 state

[英]change radio button state when parent is clicked

我有这个标记:

<div class='A'>
    <input type='radio' name='B' class='B' />
</div>
<div class='A'>
    <input type='radio' name='B' class='B' />
</div>
<div class='A'>
    <input type='radio' name='B' class='B' />
</div>

所需的功能是 select 收音机通过单击父div或收音机输入本身,如果已选中收音机,则单击父级将无效,即返回 false。

我已经让它在点击父母时改变,但是当我点击单选按钮时,什么也没有发生。 我的方法有什么问题?

jQuery:

$('input:radio').closest('div').on('click', function (e) {
    if ($('input:radio', this).prop('checked') === true) {
        console.log("returning false");
        return false;
    }
    $('input:radio', this).prop('checked', true);
    console.log("Clicked : " + $(this).attr('class'));
});

小提琴: http://jsfiddle.net/pSSc9/1/

我可以建议使用label元素而不是div吗? 您将获得相同的行为,并且根本不需要 javascript。 CSS 将负责外观。 我在你的小提琴中做了一个简单的改变,效果很好。

http://jsfiddle.net/jeffman/WQEDv/2/

$('.A').on('click', function (e) {
    if ($(e.target).is('.B')) {
        e.stopPropagation();
        // So that event does not bubble when radio is selected
    } else {
        if ($('input:radio', this).prop('checked') === true) {
            console.log("returning false");
            return false;
        }
        $('input:radio', this).prop('checked', true);
    }
    console.log("Clicked : " + $(e.target).attr('class'));
});

您的代码的问题是您在单击复选框时返回 false 。 所以你间接地做event.preventDefault()event.stopPropagation()return false;

只有在单击 div 时,您才明确需要将选中的属性设置为 true。 但是,当您单击收音机时,它会执行默认操作。 所以你需要停止事件的传播。

检查小提琴

演示

e.preventDefault(); 禁用radio按钮click事件

$('input:radio').closest('div').on('click', function (e) {
    $('input:radio', this).prop('checked', true);
});

单选按钮的click事件正在冒泡到div ,因此在这两种情况下都会触发回调。 问题是您正在阻止默认操作,在单选按钮的情况下,它是否被选中。

如果单击的元素是单选按钮,您可以添加一个退出回调的条件:

$('input:radio').closest('div').on('click', function (e) {
    if ($(e.target).is('input')) {
        return;
    }

    if ($('input:radio', this).prop('checked') === true) {
        console.log("returning false");
        return false;
    }
    $('input:radio', this).prop('checked', true);
    console.log("Clicked : " + $(this).attr('class'));
});

工作示例

暂无
暂无

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

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