jquery inArray找不到值

时间:2017-10-29 18:45:07

标签: javascript jquery

我正试图在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。如果选定的值为074,则应提醒found,但不起作用。

2 个答案:

答案 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>