使用这个我可以加载包含名称的产品,但是当我想根据索引附加某个名称时,我会得到重复项,非常感谢。
<?xml version="1.0" ?>
<catalogue>
<product>
<name>Cleaner</name>
<description>Simple Desgreaser</description>
<price>$100</price>
<image>images/lol1.png</image>
</product>
<product>
<name>CSanitiser</name>
<description>Simple Sanitiser</description>
<price>$200</price>
<image>images/lol1.png</image>
</product>
</catalogue>
function catalogueData2() {
$.ajax({
type: "GET",
url: "catalogueData.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('product').each(function(){
var name = '<p>Name: '+$(xml).find("name:eq(0)").text()+'</p>';
$("div#name").append(name);
});
}
});
}
最佳答案
$(xml).find("name:eq(0)")
是 XML 中的第一个名称,而不是 .each( 中当前产品的第一个名称)
迭代。使用 $(this).find("name:eq(0)")
仅搜索当前元素。
关于选择特定索引,也许您想要的是这样的:
function catalogData2(index) {
$.ajax({
type: "GET",
url: "catalogueData.xml",
dataType: "xml",
success: function(xml) {
var name = '<p>Name: ' + $(xml).find("name").eq(index).text() + '</p>';
$("div#name").append(name);
}
});
}
这样,catalogData2(0)
将附加 Cleaner
,catalogData2(1)
将附加 Sanitizer
.
关于javascript - 追加 .eq() 导致重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33181166/