jquery how to access the an xml node by index?
say I've an xml returned from server like this:
<persons>
<person>
<firstname>Jon</firstname>
</person>
<person>
<firstname>Jack</firstname>
</person>
<person>
<firstname>James</firstname>
</person>
</persons>
If I want to access the 3rd firstname node (passed dynamically and stored in i, assumed to be 3 here), how do I do that? My weird attempt follows:
var i=3;
$(xml).find('firstname').each(function(idx){
if (idx==i) alert($(this).text());
});
It does fetch me the right content... but it just feels wrong to me especially the looping part. Basically I'm looping through the whole tree using .each()! Is there any better approach than this? Something that'd开发者_Go百科 take me to the nth node directly like:
alert( $(xml).find('firstname')[idx].text() ); // where idx=n
I'm new to jquery so please excuse my jquery coding approach.
.eq()
Categories: Traversing > Filtering
.eq( index )
Returns: jQuery
Description: Reduce the set of matched elements to the one at the specified index.
version added: 1.1.2.
index
An integer indicating the 0-based position of the element.
http://api.jquery.com/eq/
Here's where I reached finally. Let me know if you think it can be even better!
var i=3;
alert($(xml).find('firstname').eq(i).text());
Thank you, Robert!
精彩评论