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