頁面載入時,嘗試根據 value="true" 自動勾選 checkbox,但無效果。原始碼片段:
$("#tabsList-3 input[type='checkbox']").each(function(){
if ($(this).value == "true") {
$(this).attr("checked", true);
}
});
$(this) 回傳的是 jQuery 物件,不具備原生 DOM 屬性 value。需使用 this.value(原生元素)或 $(this).val()(jQuery 方法)。
// 寫法 1:使用原生 DOM 屬性(推薦,效能最佳)
$("#tabsList-3 input[type='checkbox']").each(function(){
if (this.value === "true") { // this 指向原生 元素
this.checked = true; // 直接設定 checked 屬性
}
});
// 寫法 2:使用 jQuery val() 方法
$("#tabsList-3 input[type='checkbox']").each(function(){
if ($(this).val() === "true") {
$(this).prop("checked", true); // jQuery 1.6+ 建議用 prop()
}
});
prop("checked", true) 而非 attr("checked", "checked"),前者對應 DOM property,行為更穩定。<input type="checkbox" value="true" checked> 即可預設勾選,無需 JS。<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="tabsList-3">
<input type="checkbox" value="true" /> true
<input type="checkbox" value="false" /> false
<input type="checkbox" value="false" /> false
</div>
<script>
$(function(){
$("#tabsList-3 input[type='checkbox']").each(function(){
if (this.value === "true") this.checked = true;
});
});
</script>
</body>
</html>