使用jQuery选中/取消选中复选框?
我的页面上有一些输入文本字段,并且正在使用JavaScript显示它们的值.
I have some input text fields in my page and am displaying their values using JavaScript.
我正在使用.set("value","")
函数编辑值,添加额外的复选框字段并传递值.
I am using .set("value","")
function to edit the value, add an extra checkbox field, and to pass a value.
在这里,我要检查是否为value == 1
,则应选中此复选框.否则,应保持选中状态.
Here I want to check that if value == 1
, then this checkbox should be checked. Otherwise, it should remain unchecked.
我通过使用两个div来做到这一点,但是我对此感到不舒服,还有其他解决方案吗?
I did this by using two divs, but I am not feeling comfortable with that, is there any other solution?
if(value == 1) {
$('#uncheck').hide();
$('#check').show();
} else{
$('#uncheck').show();
$('#check').hide();
}
对于jQuery 1.6 +:
.attr()不推荐使用;使用新的 .prop()函数代替:
.attr() is deprecated for properties; use the new .prop() function instead as:
$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it
对于jQuery< 1.6:
要选中/取消选中复选框,请使用属性checked
并进行更改.使用jQuery,您可以执行以下操作:
To check/uncheck a checkbox, use the attribute checked
and alter that. With jQuery you can do:
$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it
因为您知道,在HTML中,它看起来类似于:
Cause you know, in HTML, it would look something like:
<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->
但是,您不能信任.attr()方法来获取复选框的值(如果需要).您将必须使用 .prop()方法.
However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.