使用 jquery 选中/取消选中复选框? [英] check / uncheck checkbox using jquery?

查看:53
本文介绍了使用 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.

这篇关于使用 jquery 选中/取消选中复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆