createElement 是 HTML 中應用 W3C DOM 物件模型來建立子節點(子元素)的方法。以下範例示範如何動態建立文字輸入框與按鈕,並為按鈕加上點擊事件:
<script>
window.onload = function () {
var input = document.createElement('input');
var button = document.createElement('input');
input.type = 'text';
input.id = 'text';
input.value = '1';
button.type = 'button';
button.value = '逐加';
button.style.width = '40px';
button.style.height = '23px';
document.body.appendChild(input);
document.body.appendChild(button);
button.onclick = function () {
var value = input.value;
input.value = value * 1 + 1;
}
}
</script>
這裡有個小細節值得注意:value 其實是一個字串。如果把 input.value = value * 1 + 1; 換成 input.value = value + 1;,結果會變成 111111……因為它會不斷以字串形式做串接。而 value * 1 能把 value 轉換成整數(Int),从而实现真正的數值累加。
總結: 要徹底解決 createElement 方法的相容性問題,仍需判斷瀏覽器型別。針對 IE,可以使用它特有的、能為 createElement 傳入一段合法 HTML 字串作為參數的做法;而針對非 IE 瀏覽器,則仍採用 W3C 標準方法。