jquery - 在 jquery 中从 xml 文档中检索不同的属性

标签 jquery xml

在 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/

相关文章:

c# - 将打开的 xml 字符串转换为 byte[]

xml - XPath 兄弟提取

jquery - 类似 Prototip 的 jQuery 插件

c# - 将列添加到数据集以用作 XML 父节点

jquery - 没有第一个表 td 的嵌套表 td 元素的单击事件

jquery css() 在 if else 条件下

java - 理解 xml 模式定位

java - 获取特定 xml 元素的 xsd 限制

javascript - 谷歌翻译风格选择菜单

javascript - 向下滚动页面到下一个元素