2

I'm currently working on my Stretchbox Plugin and trying to optimize and shorten the code. I've used the jquery data method to attach data to certain divs. For instance:

$('#thumbs div:last-child').data('active', true)

which sets a certain div to the active state. If i know want to find this div, i have to check each .thumb class in order to find it:

$('.thumb').each(function() {
    if($(this).data('active')){
        //Do Stuff
    }
}

This works fine, but I'm quite sure there should be a much easier way, since checking up every single .thumb div(out of 10-30) will take some performance too.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
JayJay
  • 141
  • 1
  • 3
  • 12

3 Answers3

1
$(".thumb[data-active='true']");
N.B.
  • 13,688
  • 3
  • 45
  • 55
  • Data which is set with `$.data()` [will not be available to the attribute selector](http://jsfiddle.net/Shef/unALg/). – Shef Oct 05 '11 at 07:58
  • I actually had no clue that you can't select attributes set with $.data. Thanks for pointing it out, I'll leave the answer so others at least know what's wrong (upvote is meaningless too). – N.B. Oct 05 '11 at 08:07
0

As far as I know there is no other way to do it. You could, however, create a new jQuery selector. I was going to give it a shot, but it looks like someone has already thought of it (scroll down to "Querying element data").

It will allow you to do things like this:

$(':data(active)'); //Selects all elements with "active" data

It probably won't be faster, but it might make your code neater!

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • I believe [this](http://stackoverflow.com/questions/2891452/jquery-data-selector/2895933#2895933) is a much better and broader selector. :) – Shef Oct 05 '11 at 08:13
  • Nice find! I just linked to the first one I found and didn't look any further! – James Allardice Oct 05 '11 at 08:15
0

Am I missing something? Just save it in a variable:

jQuery(function($){
  var activeDiv = [];

  $('#selector').click(function(){
    activeDiv = $('#thumbs div:last-child')
    ...
  });

  $('#executor').click(function() {
    activeDiv.each(function() {
        ...
    });
  }
});
kevin cline
  • 2,608
  • 2
  • 25
  • 38
  • This is of course working but as I already mentioned I intended to use the data method, since I'm using it for other functions too and therefore was looking for a quicker way of doing it. Thanks anyway! – JayJay Oct 05 '11 at 15:21
  • @Janik: I'm afraid that's a bit like saying that you prefer using a hammer to drive screws. The data method is used to attach data to a DOM element for later retrieval by a plugin. It can't speed up a DOM search. – kevin cline Oct 05 '11 at 17:16
  • Ok, thought it might be a another good way of doing it. Thanks for the hint. – JayJay Oct 07 '11 at 09:56