萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 動態建立 input 元素正確設定 readOnly 屬性

常見錯誤

動態建立 <input> 時,直接設定 readonly="readonly" 字串屬性 無效:

var x = document.createElement('input');
x.type = 'text';
x.value = 'ttttt';
x.id = 'xy';
x.readonly = 'readonly'; // ❌ 錯誤:屬性值為字串,非布林
// 瀏覽器不會將其視為唯讀

正確寫法:設定布林屬性 readOnly (駝峰命名)

var x = document.createElement('input');
x.type = 'text';
x.value = 'ttttt';
x.id = 'xy';
x.readOnly = true; // ✅ 正確:布林值 true,屬性名駝峰式
// 此時輸入框真正變為唯讀

關鍵差異對照表

屬性名值型別結果
readonly (全小寫)字串 'readonly'❌ 無效
readOnly (駝峰)布林 true/false✅ 生效

HTML 標籤 vs JS 設定

  • HTML 寫法:<input readonly> 或 <input readonly="readonly"> (布林屬性,有即為真)
  • JS 寫法:element.readOnly = true/false (必須用駝峰、布林值)

完整可執行範例

<button onclick="createReadOnlyInput()">建立唯讀輸入框</button>
<div id="container"></div>

<script>
function createReadOnlyInput() {
  var input = document.createElement('input');
  input.type = 'text';
  input.value = '這是唯讀內容';
  input.readOnly = true; // 關鍵行
  input.style.width = '200px';
  document.getElementById('container').appendChild(input);
}
</script>

記住:JS 操作 DOM 屬性一律用駝峰命名、布林屬性給布林值,這是避開無數坑的鐵律。

copyright © 萬盛學電腦網 all rights reserved