[英]jquery inArray not found value
I'm trying to find selected value
in array
but what i tried so far not working:我试图在
array
找到selected value
,但到目前为止我尝试的方法不起作用:
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>
it works with $.each
but i don't want use any loop my goal is get this with inArray
.它适用于
$.each
但我不想使用任何循环我的目标是使用inArray
获得它。 if selected value is 0
or 74
it should alert found
but it not works.如果选择的值为
0
或74
应该警惕found
,但它不工作。
Use indexOf()
function for find in array.使用
indexOf()
函数在数组中查找。
Chanhe type selected to integer parseInt()
(array is integers) chanhe 类型选择为整数
parseInt()
(array is integers)
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>
val
returns a string and inArray
does strict comparison 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.