简体   繁体   English

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

[英]Why is jQuery is not checking/unchecking checkbox

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>

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 还可以使用:选中过滤器来检查是否选中了复选框

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 演示: 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM