复选框选中的属性行为

Checkbox checked attribute behavior

我在 HTML 中有一个复选框类型的输入列表,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'))
})

第一个选项有什么问题?

谢谢!

attr() 和 prop() 不 return 同一件事:

.attr('checked'); // "checked"
// new property method
.prop('checked'); // true

最好使用 .prop,你将始终使用布尔值

那是因为.attr().prop()returns不同的东西。 .prop() 应用于检查布尔值 properties/attributes,如 checkedreadonlydisabled

另一方面,$("#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;
});