Select attribute values into a list
I have the following xml:
<ListOfItems>
<item myval='123' />
<item myval='342' />
开发者_如何转开发 <item myval='233' />
<item myval='444' />
</ListOfItems>
I'm parsing/traversing it with jQuery. What is a selector that would give me a list of all values in the attribute 'myval' of 'item' nodes. I'm looking for something that would give me back a list of values only. Maybe an array [ '123, '342', '233', '444' ]
Bearing in mind that I don't think those are valid elements, I'd suggest:
var listOfValues = [];
$('ListOfItems > item').each(
function(){
listOfValues.push($(this).attr('myval'));
});
Given the desire to use a single selector, the following is possible:
var myvals = $('li').map(
function(){
return this.getAttribute('myval');
}).get().join(', ');
JS Fiddle Demo.
You would need to iterate through the list of items. For example:
var itemsArray = [];
$("ListOfItems").each(function(index) {
itemsArray[index] = $(this).attr('myval');
});
Make use of the .map()
function.
var listOfItems = $('ListOfItems items').map(function() {
return $(this).attr('myval');
});
It's a really nifty function (along with $.map()
) that a lot of people miss out on.
Just keep in mind that that returns a jQuery object, so if you want to get your hands on the raw returned array, you'll have to get to it via listOfItems.get()
.
var data = new Array();
$(xml).find('item').each(function() {
data.push($(this).attr('myval'));
});
where xml
is your xml content.
or:
var array = $(xml).find('item').map(function() {
return $(this).attr('myval');
}).get();
精彩评论