开发者

What is the more correct/efficient selector?

$("select").change(function() {

                alert($("select option:selected").val());

  开发者_运维问答          });

OR

$("select").change(function() {

            alert($(this).attr("value"));

            });

I am specifically looking at the selector used in the alert. From my testing the result in the same correct values to be displayed.


They are different. The first will get the value of the first selected <option> in the DOM (in any of the <select> elements).

The second one will work fine, and of course, there are several variations that do the same thing

$("select").change(function() {
            alert($(this).val());
            });

$("select").change(function() {
            alert($('option:selected', this).val());
            });

to name a couple


First of all they are not equivalent. The first will give you the value of the selected options of any select element while the second will give you the value only of the one you changed.

So you should absolutely use the second example.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜