Вопрос

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?

Это было полезно?

Решение

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

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top