Eric's Thinking Space 程式設計 音樂 心情 有趣 Kuso

2008/03/10

JavaScript 筆記(tagName 與 setAttribute)

最近在做幫網頁壓縮JavaScript檔案的工作,

發現了幾個常碰到的問題,在這邊做個筆記,順便跟大家分享一下!


1. 關於網頁Element 的 tagName屬性時,要特別注意大小寫的問題。
ex:


var obj = event.getElementByID('xxxID');
if(obj.tagName.toUpperCase()=="DIV") //記得要先轉換大小寫之後再比對,否則容易有錯誤
{
//Do something...
}


2. 在IE中,若對自己create的Element進行setAttribute動作將無效。

ex: 下列程式碼在IE中將無法正常設定element的Attribute,但在FireFox中卻正常運作。

var input = document.createElement('input');
input.id = "name";
input.value = "new value";
input.name = "name";
input.setAttribute("onblur","alert('hello');");



解決方法:改用下列Code即可兼容於IE與FireFox


var input = document.createElement('input');
input.id = "name";
input.value = "new value";
input.name = "name";
input.onblur=function(){ alert('hello'); };