retrieving distinct attributes from xml doc in jquery
In a xml document, I would like to retrieve with jQuery the distinct attributes values for "name" attribute of the elements "product", deleting the duplicates.
However, I haven't had any success with unique() function or creating an array, as suggested in this discussion here: How to use jQuery to select XML no开发者_如何学Godes with unique text content?
Any help will be sincerly appreciated. Thank you so much in advance.
My XML:
<products>
    <product name="first"></product>
    <product name="second"></product>
    <product name="first"></product>
    <product name="first"></product>
</products>
My not working code:
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 is gettin defined for each iteration of the product element and hence the inArray is always returning -1.
Move the definition of productArray outside the each loop i.e.:
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);
                            }
                });
            }
        });
    }
First idea that comes to my head... Have you tried setting your var "productArray" global? I mean, outside of your 'each' function body? I would suspect that productArray is reset each time the code reach that point, so that it will never contain duplicated entries.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论