【问题标题】:How to check and uncheck all checkboxes in WebGrid column?如何选中和取消选中 WebGrid 列中的所有复选框?
【发布时间】:2019-12-05 02:02:17
【问题描述】:

是否有任何理由无法检查和取消选中复选框?如果我没有触摸任何复选框,它会在按钮单击事件中选中和取消选中它们。如果我手动选中一个框,则从那时起该框将不会被修改,但其余框将继续修改。

我该如何解决这个问题?

function checkAll() {
  $('#grid tbody tr').each(function () {
    if ($(this).find("td input[type=checkBox]").is(":checked")) {
      $(this).find("td input[type=checkBox]").removeAttr("checked");
      //$(this).find("td input[type=checkBox]").attr("checked", false); //also tried this
    }
    else {
      $(this).find("td input[type=checkBox]").attr("checked", true);
    }
  });
}

更新 1:

我已经制作了额外的循环来遍历每个复选框,但仍然得到相同的结果。这是更新的代码:

function checkAll() {
    var count = $('#grid tbody tr').length;
    $('#grid tbody tr').each(function () {
        $(this).find("td input[type=checkBox]").each(function () {
            if ($(this).is(":checked")) {
                $(this).attr("checked", false);
            }
            else {
                $(this).attr("checked", true);
            }
        })
    });
}

【问题讨论】:

  • 你必须让它检查每个复选框,现在你只是循环遍历每个 tr,而不是每个复选框。
  • 你能详细说明一下吗?我的印象是 if ($(this).find("td input[type=checkBox]").is(":checked")) 检查了每一行的复选框。
  • find("td input[type=checkBox]"),返回一个包含所有找到的对象的数组,.is checked 我想如果每个对象都被选中,则返回 true,尽管你是没有为每个复选框运行正确的方法
  • 据我了解,您想要实现的只是所有复选框的切换,要完成此操作,您应该创建一个 foreach,分别检查每个复选框。

标签: javascript checkbox webgrid


【解决方案1】:

根据https://api.jquery.com/attr/,您不应该使用 attr 方法来检查和取消选中 chebox,因为它指向 defaultChecked 属性,并且应该仅用于设置复选框的初始值。

可能是你的问题的原因,尝试使用 prop() 而不是 attr() (https://learn.jquery.com/using-jquery-core/faq/how-do-i-check-uncheck-a-checkbox-input-or-radio-button/)

【讨论】:

    猜你喜欢
    • 2013-05-30
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 2014-09-21
    • 2021-04-02
    • 1970-01-01
    相关资源
    最近更新 更多