سؤال

Given some sample data.xml file:

<?xml version="1.0" encoding="utf-8"?>
<data>
    <categories>
        <category id="google">
            <name>Google</name>
        </category>
    <categories>
    <display>
        <categories>
            <category idref="google"/>
        </categories>
    </display>
</data>

And some jquery code to fetch the data.xml file:

$.ajax( {
    url: '/data.xml',
    dataType: 'xml',
    success: function( data )
    {
        $data = $( data );
        // fetch categories to display
        $categories = $data.find( 'display > categories > category' );
    }
} );

What is a efficient and compact method to resolve the category elements to which the fetched elements in $categories refer to by their idref attribute?

I've come up with something like the following:

$categories.each( function() {
    var $category = $data.find( 'categories > category[id=' + $( this ).attr( 'idref' ) + ']' );
} );

But I thought there might be a more compact way of collecting the elements.

هل كانت مفيدة؟

المحلول

You can create id selectors from the idref attributes:

var referenced = $.unique($categories.map(function() {
    var $found = $data.find("#" + $(this).attr("idref"));
    return ($found.length ? $found[0] : null);
}).get());

The code above uses map() and $.unique() to build an array containing unique instances of all the referenced <category> elements.

نصائح أخرى

var $data = $( data );
var $byId = {};

$("*[id]", $data).each(function () {
  var $this = $(this);
  $byId[ $this.attr("id") ] = $this;
});

// later...
$byId["google"].find("name");  //  <name>Google</name>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top