【问题标题】:Can't check all the checkbox in JavaScript [duplicate]无法选中 JavaScript 中的所有复选框 [重复]
【发布时间】:2016-03-07 21:17:58
【问题描述】:

我在一个 Web 应用程序上工作,但在运行时,我的代码甚至无法运行。但是如果这样做

$("input[name^='show-points-']").attr("checked", false);

在控制台上,复选框取消选中。

很奇怪,因为总是在控制台中:

$("input[name^='show-points-']").attr("checked", "checked");

不工作。

在这个Jsfiddle 中,代码适用于“取消选中”功能,但不适用于“全部选中”功能。

【问题讨论】:

    标签: jquery checkbox


    【解决方案1】:

    使用prop()

    Updated Fiddle

    $("#show-all-points").change(function () {
        $("input[name^='show-points-']")
            .prop("checked", this.checked);
    });
    

    $("#show-all-points").change(function() {
      $("input[name^='show-points-']")
        .prop("checked", this.checked);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <tbody>
      <tr>
        <td>
          <input type="checkbox" checked="checked" name="show-points-pb">
        </td>
      </tr>
      <tr>
        <td>
          <input type="checkbox" checked="checked" name="show-points-pi1">
        </td>
      </tr>
      <tr>
        <td>
          <input type="checkbox" checked="checked" name="show-points-pi2">
        </td>
      </tr>
      <tr>
        <td>
          <input type="checkbox" checked="checked" name="show-points-gp">
        </td>
      </tr>
      <tr>
        <td>
          <input type="checkbox" checked="checked" name="show-points-ok">
        </td>
      </tr>
      <tr>
        <td>
          <input type="checkbox" checked="checked" name="show-points-op">
        </td>
      </tr>
      <tr>
        <td>
          <input type="checkbox" checked="checked" name="show-points-er">
        </td>
      </tr>
      <tr>
        <td></td>
        <td>Tout sélectionner/désélectionner
          <input type="checkbox" checked="checked" id="show-all-points">
        </td>
      </tr>
    </tbody>

    【讨论】:

    • oaw 4 行代码,但我不明白它在 '.prop("checked", this.checked);' 附近是如何工作的
    • @rickozoe this.checked 返回#show-all-points 复选框的选中状态,因此返回true/false 并且为所有其他复选框设置相同的设置。
    • 很棒的 jsfiddle 工作,但它仍然不适用于我的应用程序。我知道我的代码没有被破坏,因为在那之后我得到了一些说明仍然有效。
    • @rickozoe 您真的在您的应用程序中使用与 jsFiddle (1.10.1) 相同的 jQuery 版本吗?控制台中的任何错误?您的更改事件是否至少受到约束?
    • @A.Wolff 我使用的是 1.10.2,但控制台中没有错误。但似乎我不受更改事件的约束。该代码位于有效代码之间的“$(function() {}”上。
    猜你喜欢
    • 2015-03-15
    • 1970-01-01
    • 2019-09-04
    • 2018-03-24
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多