星期日, 四月 05, 2009

IE很任性

最近在寫ajax(javascript、DOM)的網頁,需要依使用者不同的選擇更新網頁文字內容(節點)

opera、Firefox都直接兩行解決:



tnode = "xmldoc.getElementsByTagName("foo")['0'].hasChildNodes().data"; //從XML產生文字節點

current.replaceChild(tnode,current.firstChild); //把舊的文字節點換成新的


但是碰到IE(我是用IE8測試)就會叫說節點不存在。
可能是XML剛好是空的(第一行),或是第一次執行所以沒有舊的文字節點(第二行)。臨時只想到用hasChildNodes()做檢查,然後code就變的好糟糕:

 


while(current.hasChildNodes())
{
current.removeChild(current.firstChild);
}

if(xmldoc.getElementsByTagName("foo")['0'].hasChildNodes())
{
tnode = document.createTextNode(xmldoc.getElementsByTagName("fax")['0'].firstChild.data);
current.appendChild(tnode); 
}


不知道有什麼好方法:q

0 意見: