2010年6月6日 星期日

IE/Firefox DOM差異性-setAttribute

最近在寫js上的一些code, 發現IE與Firefox上的一些DOM差異; 其實本來就知道有些差異了, 只是每次都會忘記然後又要重新找答案..所以趁記憶猶新的時候寫下來:)
在用DOM(Document Object Model)的時候常會用到一個方法叫做setAttribute.
例如說: 
var newtext = document.createElement('input');
newtext.setAttribute('type', 'button');
newtext.setAttribute('id', 'b1');
newtext.setAttribute('value', '按鈕');
newtext.setAttribute('onclick', 'alert(\'showme\')');
以上這些code在Firefox上是可執行的; 但是一旦換上IE之後就掛點了.
主要原因在於IE的setAttribute是不完整的, 無法支援onclick這種event.
所以比較簡單的做法就是.
newtext.onclick = function(){ alert('showme'); };
這樣在IE上就可以work well. 更詳細的內容請參考ref1.
另外, IE與FF上有其他的不同點, ref2提供了一個很好的cross site的function interface.
底下複製一份該作者(Stephen Chapman)所提供的內容.
// Cross Browser DOM
// copyright Stephen Chapman, 4th Jan 2005
// you may copy this code but please keep the copyright notice as well
var aDOM = 0, ieDOM = 0, nsDOM = 0; var stdDOM = document.getElementById;
if (stdDOM) aDOM = 1; else {ieDOM = document.all; if (ieDOM) aDOM = 1; else {
var nsDOM = ((navigator.appName.indexOf('Netscape') != -1)
&& (parseInt(navigator.appVersion) ==4)); if (nsDOM) aDOM = 1;}}
function xDOM(objectId, wS) {
if (stdDOM) return wS ? document.getElementById(objectId).style:
document.getElementById(objectId);
if (ieDOM) return wS ? document.all[objectId].style: document.all[objectId];
if (nsDOM) return document.layers[objectId];
}

沒有留言: