我正在尝试构建一个 jquery 来从 XML 文件中选择项目,但我似乎无法将它们正确链接在一起。
我已经解析了一个 XML 文件并将其附加到我的 DOM 中,这是一个示例结构
<Products>
<product1>
<Description>Pound</Description>
<ProductType>CUR</ProductType>
<CurrencyCode>GBP</CurrencyCode>
<Rate>1</Rate></ProductRate>
</product1>
<product2>
<Description>Euro</Description>
<ProductType>TCQ</ProductType>
<CurrencyCode>Eur</CurrencyCode>
<Rate>1.5</Rate></ProductRate>
</product2>
</Products>
所以我想要做的是指定我想要从 XML 中获取并显示哪些元素。我可以从 XML 中选择所有项目,我可以获取特定元素,但是当我尝试获取所有位置时,例如 (ProductType == "CUR")
我无法选择代码和评级添加到我的列表。
var $xml = $(xml);
var $list = $('#list');
$prodtype = $xml.find("ProductType");
$prodtype.each(function() {
if($(this).text() == "CUR"){
$CurrencyCode = $xml.find("CurrencyCode");
$CurrencyCode.each(function() {
$( "#list" ).append("<li><a>" + $(this).text() + " </a></li>");
});
}
});
我认为我对如何选择和存储元素感到困惑。所以在伪代码中我想我想做的是
for each element where producttype == cur
grab next 2 siblings and append to list
希望这很清楚吗?
最佳答案
var $xml = $(xml);
var $list = $('#list');
$prodtype = $xml.find("ProductType");
$prodtype.each(function() {
var self = $(this);
if( self.text() == "CUR") {
var
$CurrencyCode = self.next('CurrencyCode')
$Rate = $CurrencyCode.next('Rate')
;
$( "#list" ).append("<li><a>" + $Rate.text()+$CurrencyCode.text() + " </a></li>");
}
});
关于javascript - 使用链式查询从列表中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18508078/