【问题标题】:how to correct check checkbox and display if is checked如何更正选中复选框并显示是否选中
【发布时间】:2019-02-22 02:58:25
【问题描述】:

单击 1 个或多个复选框时,我使用此代码显示一些文本 (Checked)。 我使用on,因为复选框是动态创建的。

好像只有 IE Edge 处理不了。我必须在复选框上单击两次才能显示 Checked 文本。在所有其他浏览器中,它可以立即运行。 真的不知道代码有什么问题

<input type="checkbox" class="rafcheckbox" value="1" />
<input type="checkbox" class="rafcheckbox" value="2" />
<input type="checkbox" class="rafcheckbox" value="3" />

<div class="cb-buttons" style="display:none">Checked</div>

<script>

$(document).on('click','.rafcheckbox',function() {  
  var $checkboxes = $('.rafcheckbox').change(function() {

    var anyChecked = $checkboxes.filter(':checked').length != 0;
    $(".cb-buttons").toggle(anyChecked);
  });
});

</script>

小提琴:https://jsfiddle.net/g5tp4kjm/

【问题讨论】:

  • 您的问题很可能是因为您正在创建一个新的更改处理程序,每次单击复选框时。重复的事件处理程序将相互冲突。尤其是使用 fo 切换。
  • 我该如何解决这个问题?我应该在代码中更改什么?

标签: javascript jquery checkbox onclick dynamically-generated


【解决方案1】:
  • 由于您已经拥有元素的委托,只需将其更改为更改事件处理程序即可。
  • 在该逻辑中,切换隐藏类,但如果没有检查任何元素,则强制它具有隐藏类。

$(document).on('change','.rafcheckbox',function() {
  $('.cb-buttons').toggleClass('hide', $('.rafcheckbox:checked').length < 1);
});
.hide { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="rafcheckbox" value="1" />
<input type="checkbox" class="rafcheckbox" value="2" />
<input type="checkbox" class="rafcheckbox" value="3" />

<div class="cb-buttons hide">Checked</div>

【讨论】:

  • 我同意它有效。但我只是发现内联样式似乎是问题所在。如果我在display none 上使用内联样式的代码,问题仍然存在。但是添加 classhide 并将 display none 放入 hide 可以解决问题。至少对于 Edge
  • 您也可以使用内联样式。它只是没有toggleClass() 那样好用。
  • 感谢您的解决方案。现在很好用
【解决方案2】:

让我们尝试另一种方式。

$(document).on('click','.rafcheckbox',function() {

    if($('.rafcheckbox').is(':checked'))
    {
        //do whatever you want
    }  
    else  
    {
        //do the opposite
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    相关资源
    最近更新 更多