【问题标题】:jQuery - Reset radio buttons on clickjQuery - 单击时重置单选按钮
【发布时间】:2013-09-25 12:56:58
【问题描述】:

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);
        }
    });
});

【问题讨论】:

    标签: jquery click radio-button checked prop


    【解决方案1】:

    我认为问题在于,带有 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-07-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2013-09-23
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多