我在 HTML 中有一个 checkbox 类型的输入列表,JS 使用一个数组变量将其中一些标记为已选中,如下所示:
profileData.interests.forEach(interest => {
$(`#profile-interests input#${interest}`).attr("checked", true)
})
然后用户可以自由地检查/取消选中任何输入,完成后,他可以单击保存,我需要获取当前选中的输入列表(它们的 ID)并将它们放入一个变量中。
如果我使用此代码,输入列表将是初始列表(来自初始变量):
$("#profile-interests input").each(function() {
if ($(this).attr('checked')) {
newInterests.push($(this).attr('id'))
}
})
如果我使用此代码,输入列表是正确的,并且与我在页面上看到的一致:
$("#profile-interests input:checked").each(function() {
newInterests.push($(this).attr('id'))
})
第一个选项有什么问题?
谢谢!
答案 0 :(得分:2)
那是因为 .attr()
和 .prop()
返回不同的东西。 .prop()
应该用于检查布尔属性/属性的值,例如 checked
、readonly
、disabled
等。
另一方面,$("#profile-interests input:checked")
包含 CSS :checked
伪选择器,它将正确匹配已检查的元素,并且不依赖于 .attr()
中使用的机制(基本上,功能与使用 .prop()
。
有两种解决方案:
.prop('checked')
而不是 .attr('checked')
this.checked
,这里指的是复选框元素本身解决方案 1:使用 .prop()
:
$("#profile-interests input").each(function() {
if ($(this).prop('checked')) {
newInterests.push($(this).attr('id'))
}
});
解决方案 2:使用原生 checked
属性:
$("#profile-interests input").each(function() {
if (this.checked) {
newInterests.push($(this).attr('id'))
}
});
同样,您应该避免使用 .attr()
来切换 checked
属性。改用 .prop
:
profileData.interests.forEach(interest => {
// Option 1:
$(`#profile-interests input#${interest}`).prop("checked", true)
// Option 2:
$(`#profile-interests input#${interest}`)[0].checked = true;
});
答案 1 :(得分:1)
attr() 和 prop() 不返回相同的东西:
.attr('checked'); // "checked"
// new property method
.prop('checked'); // true
最好使用 .prop,你总是布尔值