我正试图在selected value
中找到array
,但到目前为止我没有尝试过:
var array = [0, 74];
$('select').change(function() {
var selected = $('select option:selected').val();
if ($.inArray(selected, array) != -1) {
alert('found');
} else {
alert('not found');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="0" selected="selected">----</option>
<option value="59">ss</option>
<option value="61">aa</option>
<option value="62">zz</option>
<option value="60">yy</option>
<option value="74">xx</option>
</select>
它适用于$.each
,但我不想使用任何循环,我的目标是inArray
。如果选定的值为0
或74
,则应提醒found
,但不起作用。
答案 0 :(得分:1)
使用indexOf()
函数在数组中查找。
Chanhe类型选择为整数parseInt()
(数组为整数)
var array = [0, 74];
$('select').change(function() {
var selected = parseInt($('select option:selected').val(), 10);
if(array.indexOf(selected)!=-1){
alert('found');
} else {
alert('not found');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select>
<option value="0" selected="selected">----</option>
<option value="59">ss</option>
<option value="61">aa</option>
<option value="62">zz</option>
<option value="60">yy</option>
<option value="74">xx</option>
</select>
答案 1 :(得分:0)
val
返回一个字符串,inArray
执行严格比较
var array = [0, 74];
$('select').change(function() {
var selected = $('select option:selected').val();
// convert to a number
if ($.inArray(+selected, array) != -1) {
alert('found');
} else {
alert('not found');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="0" selected="selected">----</option>
<option value="59">ss</option>
<option value="61">aa</option>
<option value="62">zz</option>
<option value="60">yy</option>
<option value="74">xx</option>
</select>