سؤال

I have a collection of elements, and whilst each has a unique String identifier, I can't safely use it's value as the elements ID as I can't guarantee that it'll only contain valid characters. As a result, I'm storing the identifiers in each of the elements jQuery .data() object. Whilst I could use a data- attribute, I don't really like the idea of using selectors where I may have to escape quotes etc., but if there's a huge efficiency bonus, it should be taken into consideration. A solution using the .data() object would be also be great as this could be applicable for any data type.

I'm wondering what the most efficient way to select a single element would be. At present, this is my solution:

function get_group($from, group) {
  var $result = $();
  $from.each(function() {
    if($(this).data("group") == group) {
      result = $(this);
      return false;
    }
  });
  return $result;
}

I iterate over each of my results until I find a match. When I do, I break from the loop. By initializing $result as an empty jQuery object, I'll always return jQuery, which I think is most consistent with standard practice and in particular the .filter() method.

I think this is better than using .filter() with a function as it explicitly returns a single (or no) item, and stops iteration as soon as it needs to, but is there a better approach?

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

المحلول

It would seem that a for loop is faster than the one you've got:

function get_group ($from, group)
    for (var i = 0; i < $from.length; i++) {
        if ($($from[i]).data("group") == group) {
            return $($from[i]);
        }
    }
    return $();
}

JSPerf: http://jsperf.com/each-vs-data-selector

EDIT: Rewrote to function, added return $()

نصائح أخرى

As you said , if each data-group is unique, you can do this -

$('[data-group="'+group+'"]')
$from.find('[data-group="' + group + '"]')
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top