[英]Checkbox checked attribute behavior
I have a list of inputs of type checkbox in HTML, and JS uses an array variable to mark some of them as checked, like this:我在 HTML 中有一个复选框类型的输入列表,JS 使用数组变量将其中一些标记为选中,如下所示:
profileData.interests.forEach(interest => {
$(`#profile-interests input#${interest}`).attr("checked", true)
})
Then the user is free to check / uncheck any inputs, and once he's done, he can click save, and I need to get the list of currently checked inputs (their IDs) and put them in a variable.然后用户可以自由地检查/取消选中任何输入,一旦完成,他可以点击保存,我需要获取当前检查的输入列表(它们的 ID)并将它们放入变量中。
If I use this code, the list of inputs will be the initial one (from the initial variable):如果我使用此代码,输入列表将是初始列表(来自初始变量):
$("#profile-interests input").each(function() {
if ($(this).attr('checked')) {
newInterests.push($(this).attr('id'))
}
})
If I use this code, the list of inputs is correct and corresponds to what I see on the page:如果我使用此代码,则输入列表是正确的,并且与我在页面上看到的内容相对应:
$("#profile-interests input:checked").each(function() {
newInterests.push($(this).attr('id'))
})
What's wrong with the first option?第一个选项有什么问题?
Thanks!谢谢!
That is because .attr()
and .prop()
returns different things.那是因为
.attr()
和.prop()
返回不同的东西。 .prop()
should be used to check for the value of boolean properties/attributes, like checked
, readonly
, disabled
and etc. .prop()
应该用于检查 boolean 属性/属性的值,例如checked
、 readonly
、 disabled
等。
On the other hand, $("#profile-interests input:checked")
contains the CSS :checked
pseudo-selector that will match checked elements properly and does not rely on the mechanism used in .attr()
(basically, functionally identical to using .prop()
.另一方面,
$("#profile-interests input:checked")
包含 CSS :checked
伪选择器,它将正确匹配检查的元素,并且不依赖于.attr()
中使用的机制(基本上,功能上与使用.prop()
。
There are two solutions:有两种解决方案:
.prop('checked')
instead of .attr('checked')
.prop('checked')
而不是.attr('checked')
this.checked
, where this refers to the checkbox element itselfthis.checked
,其中 this 指的是复选框元素本身Solution 1: Use .prop()
:解决方案 1:使用
.prop()
:
$("#profile-interests input").each(function() {
if ($(this).prop('checked')) {
newInterests.push($(this).attr('id'))
}
});
Solution 2: Use native checked
property:解决方案 2:使用本机
checked
属性:
$("#profile-interests input").each(function() {
if (this.checked) {
newInterests.push($(this).attr('id'))
}
});
On a similar note, you should avoid using .attr()
to toggle the checked
property.同样,您应该避免使用
.attr()
来切换checked
的属性。 Use .prop
instead:使用
.prop
代替:
profileData.interests.forEach(interest => {
// Option 1:
$(`#profile-interests input#${interest}`).prop("checked", true)
// Option 2:
$(`#profile-interests input#${interest}`)[0].checked = true;
});
attr() and prop() dont return the same thing: attr() 和 prop() 不返回相同的东西:
.attr('checked'); // "checked"
// new property method
.prop('checked'); // true
its better to use.prop, you'll have always boolean最好使用.prop,您将始终拥有 boolean
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.