为什么我的 select 选项通过索引而不是 .val 不起作用?
Why does my select option function via index, not .val, not work?
为什么我在两次选择中总是得到 "sort area" 作为反馈?我的失败是什么?
$('select[name="sorting"]').change(function(){
if ($(this).index = 0){
alert("sort country");
}
else if ($(this).index = 1){
alert("sort area");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<select name="sorting">
<option value="" class="country" selected>Country</option>
<option value="" class="area">Area</option>
</select>
您的代码中存在几个问题。首先=
用来设置一个值。要比较 值,您需要使用==
或===
,具体取决于您want/need 强制数据类型的方式。
其次,您查看的是 DOM 中 select
元素的索引,而不是所选 option
的索引。因此,您需要在事件处理程序中使用 find()
来获取选定的 option
并检索其 index()
。试试这个:
$('select[name="sorting"]').change(function() {
var idx = $(this).find('option:selected').index();
if (idx === 0) {
console.log("sort country");
} else if (idx === 1) {
console.log("sort area");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="sorting">
<option value="" class="country" selected>Country</option>
<option value="" class="area">Area</option>
</select>
为什么我在两次选择中总是得到 "sort area" 作为反馈?我的失败是什么?
$('select[name="sorting"]').change(function(){
if ($(this).index = 0){
alert("sort country");
}
else if ($(this).index = 1){
alert("sort area");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<select name="sorting">
<option value="" class="country" selected>Country</option>
<option value="" class="area">Area</option>
</select>
您的代码中存在几个问题。首先=
用来设置一个值。要比较 值,您需要使用==
或===
,具体取决于您want/need 强制数据类型的方式。
其次,您查看的是 DOM 中 select
元素的索引,而不是所选 option
的索引。因此,您需要在事件处理程序中使用 find()
来获取选定的 option
并检索其 index()
。试试这个:
$('select[name="sorting"]').change(function() {
var idx = $(this).find('option:selected').index();
if (idx === 0) {
console.log("sort country");
} else if (idx === 1) {
console.log("sort area");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="sorting">
<option value="" class="country" selected>Country</option>
<option value="" class="area">Area</option>
</select>