Lac*_*che 171
使用属性等于选择器
var thevalue = 'foo';
var exists = 0 != $('#select-box option[value='+thevalue+']').length;
Run Code Online (Sandbox Code Playgroud)
如果通过Javascript设置选项的值,那将无效.在这种情况下,我们可以执行以下操作:
var exists = false;
$('#select-box option').each(function(){
if (this.value == 'bar') {
exists = true;
return false;
}
});
Run Code Online (Sandbox Code Playgroud)
Mar*_*aio 15
万一你(或其他人)可能有兴趣在没有jQuery的情况下这样做:
var exists = false;
for(var i = 0, opts = document.getElementById('select-box').options; i < opts.length; ++i)
if( opts[i].value === 'bar' )
{
exists = true;
break;
}
Run Code Online (Sandbox Code Playgroud)
小智 10
这是另一个类似的选择.在我的情况下,当我构建一个选择列表时,我正在检查另一个框中的值.当我比较时,我一直在运行未定义的值,所以我以这种方式设置我的检查:
if ( $("#select-box option[value='" + thevalue + "']").val() === undefined) { //do stuff }
Run Code Online (Sandbox Code Playgroud)
我不知道这种方法是否更昂贵.
小智 6
为什么不使用过滤器?
var thevalue = 'foo';
var exists = $('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length;
Run Code Online (Sandbox Code Playgroud)
松散的比较有效,因为存在> 0为真,存在== 0为假,所以你可以使用
if(exists){
// it is in the dropdown
}
Run Code Online (Sandbox Code Playgroud)
或者结合起来:
if($('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length){
// found
}
Run Code Online (Sandbox Code Playgroud)
或者每个选择下拉列表都有选择框类,这将为您提供包含值的选择的jquery对象:
var matched = $('.select-boxes option').filter(function(){ return $(this).val() == thevalue; }).parent();
Run Code Online (Sandbox Code Playgroud)
小智 6
if(!$('#select-box').find("option:contains('" + thevalue + "')").length){
//do stuff
}
Run Code Online (Sandbox Code Playgroud)