var x = document.getElementById('x');
var output = document.createElement('p');
x.form.appendChild(output); // 關鍵行
HTMLInputElement.form 唯讀屬性,返回該輸入元素所屬的 HTMLFormElement 物件(最近的祖先 <form>)。null。x.closest('form')(現代 DOM API)。| 特性 | IE8- | 現代瀏覽器 |
|---|---|---|
input.form | 支援 | 支援 |
但代碼中使用的 oninput、textContent、valueAsNumber **IE8- 不支援**。
// 事件
if (x.addEventListener) {
x.addEventListener('input', handler);
} else {
x.attachEvent('onpropertychange', function(e) {
if (e.propertyName === 'value') handler();
});
}
// 文字內容
output.textContent = str; // 現代
output.innerHTML = str; // IE8- 兼容(注意 XSS)
// 數值
var v = parseFloat(x.value) || 0; // 替代 valueAsNumber
var form = x.form || x.closest('form');
if (form) form.appendChild(output);