Setting quot;checkedquot; for a checkbox with jQuery(设置“选中对于带有 jQuery 的复选框)
问题描述
我想做这样的事情来使用 jQuery 勾选 checkbox
:
I'd like to do something like this to tick a checkbox
using jQuery:
$(".myCheckBox").checked(true);
或
$(".myCheckBox").selected(true);
这样的事情存在吗?
推荐答案
现代jQuery
使用.prop()
:
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
DOM API
如果您只使用一个元素,您可以随时访问底层 HTMLInputElement
并修改其 .checked
属性:
$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;
使用 .prop()
和 .attr()
方法的好处是它们将对所有匹配的元素进行操作.
The benefit to using the .prop()
and .attr()
methods instead of this is that they will operate on all matched elements.
.prop()
方法不可用,需要使用.attr()
.
The .prop()
method is not available, so you need to use .attr()
.
$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);
请注意,这是 所使用的方法jQuery 1.6 版之前的单元测试 并且比使用 $('.myCheckbox').removeAttr('checked');
更可取,因为如果最初选中该框,后者将更改对 .reset()<的调用行为/code> 在任何包含它的表单上——一个微妙但可能不受欢迎的行为变化.
Note that this is the approach used by jQuery's unit tests prior to version 1.6 and is preferable to using $('.myCheckbox').removeAttr('checked');
since the latter will, if the box was initially checked, change the behaviour of a call to .reset()
on any form that contains it – a subtle but probably unwelcome behaviour change.
有关更多上下文,可以在 版本 1.6 发行说明 和 Attributes vs. Properties 部分.prop()
文档.
For more context, some incomplete discussion of the changes to the handling of the checked
attribute/property in the transition from 1.5.x to 1.6 can be found in the version 1.6 release notes and the Attributes vs. Properties section of the .prop()
documentation.
这篇关于设置“选中"对于带有 jQuery 的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:设置“选中"对于带有 jQuery 的复选框


基础教程推荐
- 在 contenteditable 中精确拖放 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01