0

jsfiddle

http://jsfiddle.net/cCBUh/2/

信息

  • 我有3个选择。只点击标签,而不是单选按钮。
  • 单击不同的标签时,会选中不同的单选按钮。
  • 在控制台中,当单击标签时,它会显示“已单击”,以确保发生这种情况。
  • 单击两次相同的标签时,控制台会显示“已选中”,告诉我们它已被选中。
  • 如果标签已经被选中,它应该从所有单选按钮中删除选中,重新设置它,就像从一开始一样。

问题

当第二次单击单选按钮时,不要从所有单选按钮中删除选中的选项。这是为什么?解决方案?

HTML

<div class="panel">
    <label for="radio-1">Radio 1</label>
    <label for="radio-2">Radio 2</label>
    <label for="radio-3">Radio 3</label>
    <input type="radio" id="radio-1" name="group-1">
    <input type="radio" id="radio-2" name="group-1">
    <input type="radio" id="radio-3" name="group-1">
</div>

jQuery

jQuery(document).ready(function($) {
    $('.panel label').on( "click", function(e) {
        console.log('clicked');
        var my_id = $(this).attr('for');
        if( $('.panel #' + my_id).is(':checked') ) {
            console.log('checked');
            $('.panel input[type="radio"]').prop('checked', false);
        }
    });
});
4

1 回答 1

4

我认为问题在于,具有 id 属性的标签上的默认点击行为会强制执行此操作。我更改了您的 javascript 以执行您想要的操作,并添加了更多调试:

http://jsfiddle.net/cCBUh/15/

jQuery(document).ready(function($) {
    $('.panel label').on( "click", function(e) {
        // prevent the html to automatically check the corresponding checkbox
        e.preventDefault();
        var my_id = $(this).attr('for');
        console.log('clicked: ' + my_id);
        if( $('#' + my_id).is(':checked') ) {
            console.log('checked: ' + my_id);
            $('#' + my_id).prop('checked', false);
        } else {
            console.log('check now: ' + my_id);
            $('#' + my_id).prop('checked', true);
        }
    });
});

但是您可能还想将该行为应用于单选按钮本身的 onClick?

于 2013-09-20T08:23:23.400 回答