document.createElement鍒涘缓鐨<button>鐨則ype灞炴т负鍙
document.createElement鍒涘缓鐨<button>锛屽嵆浣夸笉杩藉姞鍒癉OM鏍戜腑锛屽湪IE涓篃涓嶈兘淇敼鍏秚ype灞炴у拰button灞炴э紝鍏朵粬娴忚鍣ㄨ缃篃鍙兘涓嶇敓鏁堛
娴嬭瘯浠g爜
娴嬭瘯浠g爜涓伩寮浜唗ype鐨勯粯璁ゅ硷紝鍥犱负<button>鐨則ype灞炴у湪IE涓嬬殑榛樿鍊兼槸button锛岃屽湪鍏朵粬娴忚鍣ㄩ粯璁ゆ槸submit 銆傛垜浠钩鏃跺湪浣跨敤鏃讹紝寤鸿鏄惧紡鐨勫0鏄巘ype灞炴с
Always specify the type attribute for the button. The default type for Internet Explorer is “button”, while in other browsers (and in the W3C specification) it is “submit”.
// 鍒涘缓input
var iptEl = document.createElement('input');
iptEl.type = 'password'; // 閬垮厤榛樿鍊
iptEl.name = 'damon';
document.body.appendChild(iptEl);
// 鍒涘缓button
var btnEl = document.createElement('button');
btnEl.type = 'reset'; // IE涓嬭繖閲屾姤閿欎簡
btnEl.name = 'damon';
document.body.appendChild(btnEl);
alert(document.getElementsByTagName('input')[0].type +','+
document.getElementsByTagName('button')[0].type);
娴嬭瘯缁撴灉
| 娴忚鍣 | <input> | <button> |
|---|---|---|
| IE 6 | Yes | No |
| IE 7 | Yes | No |
| IE 8 | Yes | No |
| IE 9 | Yes | Yes |
| Firefox 4.0 | Yes | Yes |
| Chrome 13(DEV) | Yes | No |
| Safari 5 | Yes | No |
| Opera 11 | Yes | Yes |
浠庢祴璇曠粨鏋滃彲浠ョ湅鍒帮紝<input>骞舵棤姝ら棶棰樸
瑙e喅鏂规
As of Microsoft Internet Explorer 5, the type property is read/write-once, but only when an input element is created with the createElement method and before it is added to the document.
鍗冲彧鏈塪ocument.createElement鍒涘缓鐨刬nput鍏冪礌锛屽湪鍏跺鍔犲埌DOM鏍戜箣鍓嶅厑璁稿type灞炴ц繘琛屼竴娆℃洿鏀广備絾浠庡疄闄呮儏鍐垫潵鐪嬪苟闈炲姝わ紝杩欎釜浠呮湁鐨勪竴娆¤缃畉ype鐨勬満浼氬湪鍒涘缓鏃跺氨鐢ㄦ帀浜嗐備粠涓婇潰鐨勬祴璇曠粨鏋滅湅锛岃繖涓棶棰樼洿鍒癐E9鎵嶄慨澶嶃
閽堝IE锛document.createElement(tag)涓紝tag鍙互鏄甫鏈夊睘鎬х殑瀛楃涓诧紝鍒涘缓鏃跺嵆灏唗ype鍜宯ame鍐欎笂鍗冲彲銆
Attributes can be included with the sTag as long as the entire string is valid HTML.
瀵瑰叾浠栫殑鐜颁唬娴忚鍣(Chrome銆丼afari绛)浣跨敤setAttribute鍗冲彲锛屾垨鑰呬娇鐢document.createAttribute鍒涘缓灞炴ц妭鐐癸紝鍐嶉氳繃setAttributeNode鍔犲埌鍏冪礌鑺傜偣涓娿
鏂规硶涓锛
var btnEl;
try {
btnEl = document.createElement('');
} catch(e){}
if(! btnEl) {
btnEl = document.createElement('button');
btnEl.setAttribute('type', 'reset');
btnEl.setAttribute('name', 'damon');
}
document.body.appendChild(btnEl);
alert(document.getElementsByTagName('button')[0].type +','+
document.getElementsByTagName('button')[0].name);
鏂规硶浜岋細
var btnEl;
try {
btnEl = document.createElement('');
} catch(e){}
if(! btnEl) {
btnEl = document.createElement('button');
var aType = document.createAttribute('type');
var aName = document.createAttribute('name');
aType.value = 'reset';
aName.value = 'damon';
btnEl.setAttributeNode(aType);
btnEl.setAttributeNode(aName);
}
document.body.appendChild(btnEl);
alert(document.getElementsByTagName('button')[0].type +','+
document.getElementsByTagName('button')[0].name);