Frage

In JQuery, we have two ways for SELECT onchage:

1. Use the .change by specifying the name

HTML:

<select name="a">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

JQuery:

$('select[name=a]').change(function(){
    alert($(this).val());
});

2. Use the .change by specifying the id

HTML:

<select id="a">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

JQuery:

$('#a').change(function(){  
    alert($(this).val());
});

So, given a smaller or larger list of elements, which one is faster/more efficient when using JQuery?

What would be the best practice?

War es hilfreich?

Lösung

First of all there are lots of other ways to select any element (including a select element) in jQuery.
Selecting elements by id is always better as it supposed to be unique and gives results faster

Andere Tipps

If you want to apply all the elements then use first.Otherwise use second

1) Id selectors are the fastest
2) Tag name selectors are next fastest
3) Class name selectors with no tag name are the slowest

so you can use id selector.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top