单击父级时更改单选按钮状态

时间:2013-08-02 17:03:22

标签: javascript jquery html input radio

我有这个标记:

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

所需的功能是通过单击父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/

4 个答案:

答案 0 :(得分:3)

我建议使用label元素代替div s吗?您将获得相同的行为,并且根本不需要javascript。 CSS将照顾外观。我在你的小提琴中做了那么简单的改变,它运作良好。

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

答案 1 :(得分:1)

$('.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时,才明确需要将checked属性设置为true。但是当你点击收音机时,它会执行默认操作。所以你需要停止事件的传播。

<强> Check Fiddle

答案 2 :(得分:1)

DEMO

e.preventDefault();停用了radio按钮click活动

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

答案 3 :(得分:1)

来自单选按钮的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'));
});

Working example