jQuery

jQuery 提供了 attr() 和 prop() 方法来完成任务。
选择取决于 jQuery 版本。
让我们看看每个例子。

如何使用 JavaScript 和 jQuery 选中和取消选中复选框

要选中和取消选中复选框,我们可以使用下面描述的 JavaScript 或者 jQuery 方法。

属性Attributes 与属性Properties的区别

对于 jQuery 1.6 版本,prop() 方法提供了一种检索property值的方法,而 attr() 方法检索 attributes。
checked 是一个布尔attribute属性,这意味着如果该attribute存在,则相应的property为真,即使该attribute没有值或者attribute设置为空字符串值或者“假”, property 都为真。
请务必记住,checked attribute属性与checked 属性不对应。
选中的attribute属性值不会随着复选框的状态而改变,而选中的属性会改变。

prop()

我们可以使用 prop() 方法选中或者取消选中复选框,例如单击按钮。

该方法需要 jQuery 1.6+。

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
  </head>
  <body>
    <p><input type="checkbox" id="checkId"> Are you sure?</p>
    <button type="button" class="check">Yes</button>
    <button type="button" class="uncheck">No</button>
    <script>
      $(document).ready(function() {
          $(".check").click(function() {
              $("#checkId").prop("checked", true);
            });
          $(".uncheck").click(function() {
              $("#checkId").prop("checked", false);
            });
        });
    </script>
  </body>
</html>

attr()

jQuery attr() 方法可用于选中和取消选中 jQuery 1.5 以下版本的复选框:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
  </head>
  <body>
    <p><input type="checkbox" id="checkId"> Are you sure?</p>
    <button type="button" class="check">Yes</button>
    <button type="button" class="uncheck">No</button>
    <script>
      $(document).ready(function() {
          $(".check").click(function() {
              $("#checkId").attr("checked", true);
            });
          $(".uncheck").click(function() {
              $("#checkId").attr("checked", false);
            });
        });
    </script>
  </body>
</html>

JavaScript

使用以下代码使用 JavaScript 选中和取消选中复选框:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
  </head>
  <body>
    <form>
      <p><input type="checkbox" id="checkId"> 请确认?</p>
      <button type="button" class="check" onclick="check()">Yes</button>
      <button type="button" class="uncheck" onclick="uncheck()">No</button>
    </form>
    <script>
      //create check function 
      function check() {
        let inputs = document.getElementById('checkId');
        inputs.checked = true;
      }
      //create uncheck function 
      function uncheck() {
        let inputs = document.getElementById('checkId');
        inputs.checked = false;
      }
      window.onload = function() {
        window.addEventListener('load', check, false);
      }
    </script>
  </body>
</html>
日期:2020-06-02 22:16:09 来源:oir作者:oir