(其實這跟 AJAX 無關,只是因為剛好在學 AJAX 時碰到,就歸在這一類吧......XP)
在實作第三章程式時,發現 firstchild 和 lastchild 在 IE 上運作正常,但在 FF 就無法運作,著實令人困擾。
上網查了資料,終於得知答案,
其實原因在這本書一開頭就有提到:
...... 問題在於資料裡包含的多餘的空白與換行。 Internet Explorer 並不將空白部分視為節點, |
在論壇也有人做相同解答:
| I suppose it would be more accurate to say that IE does not include white space characters between elements as a text nodes, while other browsers do, and since text nodes are considered to be children of an element, you end up needing to check the nodeType of nodes returned via properties which include firstChild and lastChild. |
那有沒有解決方式呢?
有。
解答在這篇網誌文章中:
Use getNextSibling(element) instead of element.nextSibling. function getNextSibling(startBrother) function getFirstChild(elm) |
至於 lastchild 的解法呢?
在這篇有提到:
| var node=document.getElementById( "abc" ).lastChild; if( node.nodeType != 1 ) node = node.previousSibling; node.style.color = "red"; |
不過以上方法我沒實際測過,
歡迎測過的人給予心得或意見喔~~ ^^
- firstChild and nextSibling differences between Firefox and Explorer | Marcus Nyberg
- FireFox firstChild issue - Dev Shed
- Firefox - :first-child, :only-child, and :last-child Broken Since 2001 | kaioa.com
- firstchild doesn't work in firefox : firstchild, firefox
- Agave Group » Blog Archive » Firefox DOM - whitespace and newline
- 小飘的排泄处 - FireFox 下如何取lastChild - 腾讯博客 - Qzone












