動態建立 <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 | ✅ 生效 |
<input readonly> 或 <input readonly="readonly"> (布林屬性,有即為真)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 屬性一律用駝峰命名、布林屬性給布林值,這是避開無數坑的鐵律。