[英]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()
返回不同的東西。 .prop()
應該用於檢查 boolean 屬性/屬性的值,例如checked
、 readonly
、 disabled
等。
另一方面, $("#profile-interests input:checked")
包含 CSS :checked
偽選擇器,它將正確匹配檢查的元素,並且不依賴於.attr()
中使用的機制(基本上,功能上與使用.prop()
。
有兩種解決方案:
.prop('checked')
而不是.attr('checked')
this.checked
,其中 this 指的是復選框元素本身解決方案 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;
});
attr() 和 prop() 不返回相同的東西:
.attr('checked'); // "checked"
// new property method
.prop('checked'); // true
最好使用.prop,您將始終擁有 boolean
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.