简体   繁体   English

使用javascript / jQuery在选择框中搜索值

[英]search for values in select box using javascript/jQuery

I am trying to search the options within a HTML select to find which options have values matching any element in an array 我试图在HTML选择中搜索选项,以查找哪些选项的值与数组中的任何元素匹配

For example, I have an array of integer values like so: 例如,我有一个整数值数组,如下所示:

var arrTaken = [641, 640];

and I have a select element like so: 我有一个像这样的选择元素:

<select id="Substance3" name="Substance_3">
<option value="640">A</option>
<option value="641">B</option>
<option value="642">C</option>
<option value="643">D</option>
<option value="644">E</option>
</select>

Then I loop through the options on the select in an attempt to find any element value matching: 然后我遍历select上的选项,试图找到任何匹配的元素值:

$('#Substance3 > option').each(function(index, element)
{
    console.log('current element value is: ' + element.value);
    var index = arrTaken.indexOf(element.value);
    console.log('element is at index: ' + index);
});

The problem is that the index is returned as -1, meaning the value was not found in the array. 问题是索引返回-1,表示在数组中找不到该值。 However, trying with 但是,尝试着

var index = arrTaken.indexOf(640);

works 作品

What am I doing wrong here? 我在这做错了什么?

Convert the value to a number first: 首先将值转换为数字:

 var index = arrTaken.indexOf(+element.value);
 //                           ^ unary plus

.indexOf uses strict equality comparison (same as === ). .indexOf使用严格的相等比较(与===相同)。 element.value returns a string, while your array contains numbers. element.value返回一个字符串,而您的数组包含数字。

DEMO DEMO

将数组声明为此

var arrTaken = ['641', '640'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM