我将以下 XML 放在 javascript 中名为 RoomPriceInfo 的 var 中:
<?xml version="1.0" encoding="UTF-8"?>
<BkgItemHotelRoomPrices CurrCode="EUR">
<RoomType Code="DB" Count="1" Desc="Double" Age="0">
<PriceInfo EndDate="2011-12-17" AgentMarkup="0.0" MarkupPerc="0.1075" FitRdg="0.25" MarkupPrice="48.73" AgentPrice="48.75" StartDate="2011-12-11" Nights="7" FitRdgPrice="48.75" CurrDec="2" CurrDecPrice="48.75" SuppPrice="44.0"/>
</RoomType>
</BkgItemHotelRoomPrices>
和下面的代码:
DBRoomPrice = RoomPriceInfo.doXPath("//RoomType[@Code='DB']");
alert(DBRoomPrice[0].children.length);
在 Ubuntu 上的 FF7 和 WinXP 上的 FF8 下,我得到一个正确的警报 1。然而,在 WinXP 的 IE8 和 Windows 7 的 IE9 下没有任何反应。它只是静静地死去。
请问有人能解释一下吗?如果我在 DOM 对象上执行 getElementById
,然后在该对象上请求子项,那么 IE8 和 IE9 会正常运行。
最佳答案
Internet Explorer(包括版本 11!)不支持 XML 元素的 .children
属性。
如果要获取子元素的个数,使用element.childElementCount
(IE9+):
element.children.length; // Does not work in IE on XML elements
element.childElementCount; // Works in every browser
如果你只是想知道一个元素是否有子元素,你也可以检查是否element.firstElementChild
(或 element.lastElementChild
)不为空。此属性在 IE9+ 中受支持:
element.children.length === 0; // All real browsers
element.firstElementChild !== null; // IE 9+
如果要遍历 XML 节点的所有子元素,请使用 childNodes
并通过它们的 nodeType
排除非元素节点:
for (var i = 0, len = element.childNodes.length; i < l; ++i) {
var child = element.childNodes[i];
if (child.nodeType !== 1/*Node.ELEMENT_NODE*/) continue;
// Now, do whatever you want with the child element.
}
关于javascript - IE9 未获取 XML 节点的 'children',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8210236/