$("select").change(function() {
alert($("select option:selected").val());
});
或者
$("select").change(function() {
alert($(this).attr("value"));
});
我专门查看警报中使用的选择器。根据我的测试,结果显示在相同的正确值中。
他们是不同的。第一个将获得<option>
DOM 中第一个选择的值(在任何<select>
元素中)。
第二个可以正常工作,当然,有几个变体可以做同样的事情
$("select").change(function() {
alert($(this).val());
});
$("select").change(function() {
alert($('option:selected', this).val());
});
命名一对
首先,它们是不等价的。第一个将为您提供任何 select
元素的选定选项的值,而第二个将为您仅提供您更改的选项的值。
所以你绝对应该使用第二个例子。