首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

HTML 中 value="true" 的 checkbox 無法被選中?jQuery 選取器寫法錯誤

     編輯:程式設計綜合問答

問題重現

頁面載入時,嘗試根據 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,行為更穩定。
  • 若 checkbox 為動態生成,請改用事件委派或在生成後初始化。
  • HTML5 中 <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>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved