我有一个复选框,我正在使用jQuery检查和取消选中,但是我遇到了大多数主流浏览器的错误:
如果我更改要检查的复选框,然后取消选中,然后再使用jquery再次检查,即使检查元素已经正确添加了已检查的属性,小十字也不再显示。
我使用以下代码更改了checked属性:
$('.checkbox').attr('checked', true);
替换false
取消选中此框。
有没有人遇到过这个问题或知道如何解决这个问题?
Here is a fiddle that replicates the problem - 点击支票,然后取消选中,然后重新检查,您会看到不再显示勾号
答案 0 :(得分:5)
使用.prop()代替.attr()
$("#check").click(function (e) {
e.preventDefault();
$("#chk").prop("checked", true);
});
$("#uncheck").click(function (e) {
e.preventDefault();
$("#chk").prop("checked", false);
});
答案 1 :(得分:0)
您必须使用 prop :$("#chk").prop("checked", true);
<强> http://jsfiddle.net/daL3R/2/ 强>
$("#check").click(function(e) {
e.preventDefault();
//$("#chk").attr("checked", true);
$("#chk").prop("checked", true);
});
$("#uncheck").click(function(e) {
e.preventDefault();
//$("#chk").attr("checked", false);
$("#chk").prop("checked", false);
});
答案 2 :(得分:0)
$("#chk").prop("checked", false);
$("#chk").prop("checked", true);
答案 3 :(得分:0)
使用它:
$("#check").click(function() {
// e.preventDefault();
$("#chk").prop("checked", true);
});
$("#uncheck").click(function() {
//e.preventDefault();
$("#chk").prop("checked", false);
});