在 xml 文档中,我想使用 jQuery 检索元素“product”的“name”属性的不同属性值,并删除重复项。
但是,我在 unique() 函数或创建数组方面没有取得任何成功,正如本次讨论中所建议的: How to use jQuery to select XML nodes with unique text content?
任何帮助将不胜感激。 提前非常感谢您。
我的 XML:
<products>
<product name="first"></product>
<product name="second"></product>
<product name="first"></product>
<product name="first"></product>
</products>
我的不工作代码:
function getName() {
$.ajax({
type: "GET",
url: xmlFile.xml,
dataType: "xml",
success: function(xml) {
$(xml).find('product').each(function(){
var name = $(this).attr('name');
var productArray = new Array();
if( jQuery.inArray(name, productArray) == -1 ){
$('<p></p>').html(name).appendTo('body');
productArray.push(name);
}
});
}
});
}
最佳答案
productArray 是为产品元素的每次迭代定义的,因此 inArray 始终返回 -1。
将productArray的定义移到each循环之外,即:
function getName() {
$.ajax({
type: "GET",
url: xmlFile.xml,
dataType: "xml",
success: function(xml) {
var productArray = new Array();
$(xml).find('product').each(function(){
var name = $(this).attr('name');
if( jQuery.inArray(name, productArray) == -1 ){
$('<p></p>').html(name).appendTo('body');
productArray.push(name);
}
});
}
});
}
关于jquery - 在 jquery 中从 xml 文档中检索不同的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7323373/