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:
<items>
<item>
<categories>
<cat>Category 1</cat>
<cat>Category 2</cat>
</categories>
</item>
<item>
<categories>
<cat>Category 2</cat>
<cat>Category 3</cat>
</item>
</items>
I'd like to generate a select list like:
<select>
<option>Category 1</option>
<option>Category 2</option>
<option>Category 3</option>
</select>
So far all of my attempts produce a duplicate "Cat开发者_JAVA百科egory 2" option node. I attempted to make use of the $.unique() method, but the results make me think it's only comparing the node name, not the text content. Here is my latest hackery that does not work:
var filters = $("cat",xmldoc);
filters = $.unique(filters);
$(filters).each(function()
{
$("select").append("<option>" + $(this).text() + "</option>");
});
I can think of a number of standard javascript tricks to make this happen, but am hoping there's a nice, elegant jQuery way to pull this off.
Any tips or tricks would be greatly appreciated.
Thanks!
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($('<option>').attr('val', this).attr('text', this));
});
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.
精彩评论