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 的复选框
- 如何显示带有换行符的文本标签? 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01