我从 AJAX 调用中得到以下 XML:
<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);
}