的XML節點我從一個AJAX調用下面的XML:遍歷使用JavaScript
<cars>
<car id="Spyder">
<year>1946</year>
<power>150bhp</power>
<description>A classic car with smooth lines, rounded lights and recessed exhaust.</description>
<image>1.jpg</image>
</car>
<car id="Solaris">
<year>1935</year>
<power>145bhp</power>
<description>A revisionist design, encompassing aggressive engine lines balanced with smooth curves.</description>
<image>2.jpg</image>
</car>
<car id="Career">
<year>1932</year>
<power>250bhp</power>
<description>A triumph of engineering with independent suspension and brakes.</description>
<image>3.jpg</image>
</car>
</cars>
我試圖獲取所有有關汽車的信息。我試着訪問firstChild.text
等。這是我嘗試過的最新代碼,但我仍然收到一個異常,說Object #<Element> has no method 'getFirstChild'
,所以大概有getFirstChild函數的一些問題。
有人請指導我如何繼續前進,遍歷和獲取數據?
這裏是我的代碼:
for (var i = 0; i < data.getElementsByTagName("car").length; i++) {
carname = data.getElementsByTagName("car")[i].getAttribute("id");
year = data.getElementsByTagName("car")[i].getFirstChild().getTextContent();
power = data.getElementsByTagName("car")[i].getSecondChild().getTextContent();
description = data.getElementsByTagName("car")[i].getThirdChild().getTextContent();
image = data.getElementsByTagName("car")[i].getFourthChild().getTextContent();
alert(carname + year + power + description + image);
}