How to use jQuery to select XML nodes with unique text content?

前端 未结 1 899
遇见更好的自我
遇见更好的自我 2021-01-22 05:25

I\'m attempting to pull a list of unique text entries from an XML document \"the jQuery way\" and am hitting a wall.

From this XML:


  <         


        
1条回答
  •  有刺的猬
    2021-01-22 06:11

    The cat elements are not duplicates just because they have the same text content. They're still elements with their own, different identity, and consequently unique will not remove them.

    You'll have to read the text contents into an array instead, and then remove duplicates from the Array-of-String.

    Unfortunately, you also can't use unique afterwards on the Array-of-String, because it only supports DOM element items.

    I'd just do the dupe removal when building the list:

    var cats= [];
    $('cat', xmldoc).each(function() {
        var text= $(this).text();
        if ($.inArray(text, cats)===-1)
            cats.push(text);
    });
    

    Then add each option to the select:

    $.each(cats, function() {
        $('select').append($('

    The option text needs to be set using attr and not by passing in the whole element as HTML. When you make HTML from text, you have to HTML-escape any text strings you are injecting into the HTML, otherwise you'll have potential cross-site-scripting security holes.

    0 讨论(0)
提交回复
热议问题