开发者

What is the fastest Javascript (jquery) method to select elements that have certain pieces of data

开发者 https://www.devze.com 2023-04-06 10:54 出处:网络
I have a set of results (a list of cars) which are displayed in div\'s. I want to use jquery to allow me to filter these results e.g. I want a checkbox that says \'Air Conditioning\' that when checked

I have a set of results (a list of cars) which are displayed in div's. I want to use jquery to allow me to filter these results e.g. I want a checkbox that says 'Air Conditioning' that when checked hides all of the 'Non-aircon cars'.

There are several attributes that each car has:

  • air
  • trans
  • group
  • etc.

I have thought of 3 methods which I can add this data to the page in a selectable fashion, which one will be the fastest? i.e. is there a clear winner?

1. Add classes to each result:

<div class="air_0 trans_1 group_3">Car</div>

and use jquery like:

$('.air_1').hide();

2. Each result has a uniue id which 开发者_JAVA百科is referenced in a js array

Var tags =  new array();
tags['air_1'] = 'unique_id_1';
tags['trans_0']['unique_id_1'] = true;

and use jquery like:

$.each(Tags['air_1'], function(i, result)
 {
  $('#'+result).hide();
 });

3. Add some extra attributes to the HTML (invalidating it)

<div air=”1” fuel=”3”></div>

and use jquery like:

$('div[air=1]').hide();


Adding classes is the way to go.

Although, I don't think that you need true/false classes (air_0, air_1, etc). You should just add the classes of what a car doesn't have to it (for example <div classes="air">Car</div> doesn't have air conditioning). This is definitely the best way to do this because generating all of the data is quite simple, and it's really easy to manage the results with jQuery's .show()/.hide() functions. It also requires very little code, which makes it extremely fast. I've written lots of functions that require divs, inside divs, inside divs (mild exaggeration), lots of data and regex, but it's all just seems a bit too complicated compared to a few classes and some .show()/.hide() use.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号