为什么 jQuery 没有选中/取消选中复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18439468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:37:49  来源:igfitidea点击:

Why is jQuery is not checking/unchecking checkbox

javascriptjquerycheckbox

提问by necromancer

When I run the following self-contained code, the checkbox gets checked and unchecked once but thereafter it doesn't even though the messages seem to imply the toggling.

当我运行以下自包含代码时,复选框被选中和取消选中一次,但此后即使消息似乎暗示切换,它也不会。

<html>  
<head>
<title>dummy</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<input id="fc" type="checkbox" />
<script>
function f () {
  if (typeof $("#fc").attr("checked") !== 'undefined') {
    alert("checked, unchecking");
    $("#fc").removeAttr("checked");
  } else {
    alert("unchecked, checking");
    $("#fc").attr("checked", "checked");
  }
  setTimeout(f, 1000);
}
setTimeout(f, 1000);
</script>
</body>
</html>

回答by Arun P Johny

need to use .prop() instead of .attr() to check and uncheck checkboxes

需要使用 .prop() 而不是 .attr() 来检查和取消选中复选框

$("#fc").prop("checked", true);// true to check false to uncheck

Also use :checked filter to check whether a checkbox is checked

还可以使用 :checked 过滤器来检查复选框是否被选中

function f () {
    if ($("#fc").is(":checked")) {
        alert("checked, unchecking");
        $("#fc").prop("checked", false);
    } else {
        alert("unchecked, checking");
        $("#fc").prop("checked", true);
    }
    setTimeout(f, 1000);
}
setTimeout(f, 1000);

The above given sample can be simplified as

上面给出的样本可以简化为

function f () {
    $("#fc").prop("checked", !$("#fc").is(":checked"));
}
setInterval(f, 1000);

Demo: Fiddle

演示:小提琴