开发者

What is the most efficient jQuery selector in the following mark-up?

I currently have some third party client-side "magic widgets" library that I have to deal with... :) All I have to do really is to add some small amount of behavior to those things with jQuery to accommodate for some simple business rules. A lot of times, I find myself selecting a bunch of elements in the same way. Since "magic widgets" are already super heavy on JS, and I even notice it on my fast machine, I was trying to keep my own JS to an absolute minimum. So, given that the user clicks on one of the following inputs, what is the most efficient way to select all the inputs, including开发者_JS百科 the clicked one, in the following structure with jQuery?

<div>
    <label><input ... /></label>
    <label><input ... /></label>
    <label><input ... /></label>
</div>


First of all, your inputs shouldn't be wrapped in labels, but that's a different argument.

The fastest way is probably:

$('input').click(function(){
   var siblings = $(this).closest('div').find('input');
});

This will select your clicked input again too, though. If that's a problem, try:

$('input').click(function(){
   var siblings = $(this).closest('div').find('input').not($(this));
});

If you were using correct markup so that the label tags preceded each input element, then your HTML would look like

<div>
    <label for="input1" /><input id="input1" ... />
    <label for="input2" /><input ... />
    <label for="input3" /><input ... />
</div>

Then your jQuery code becomes way easier:

$('input').click(function(){
   var siblings = $(this).siblings('input');
});


Well, assuming none of the elements in that markup have unique id's or class names, the most efficient selector you can use is a combination of tag names and the >, or first-child selector:

$("div > label > input");


$("div>label>input") I presume. Although you could give each input a common class and do $("input.class").


it depends. if the markup only consists of your fragment than:

$('input');

All modern broswers have a cache to tags.

If your looking for the inputs in within the div add an id to the div:

<div id="input_fields">
    <label><input ... /></label>
    <label><input ... /></label>
    <label><input ... /></label>
</div>

and use this selector:

$('#iput_fields > label > input');

The id is important since it is the fastest possible query a browser can perform.


Seems like using class name better than using tag names without any parent. Here is the test for it for test your self.

Maybe more complex html structure give different results.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜