Answers:
如果已经存在,则评估为true:
$("#yourSelect option[value='yourValue']").length > 0;
使用jQuery的另一种方式:
var exists = false;
$('#yourSelect option').each(function(){
if (this.value == yourValue) {
exists = true;
}
});
.length
可能那样判断空白的长度,因此不太容易出错。
对我有帮助:
var key = 'Hallo';
if ( $("#chosen_b option[value='"+key+"']").length == 0 ){
alert("option not exist!");
$('#chosen_b').append("<option value='"+key+"'>"+key+"</option>");
$('#chosen_b').val(key);
$('#chosen_b').trigger("chosen:updated");
}
});
我有一个类似的问题。我没有通过选择控件的循环每次都通过dom运行搜索,而是将jquery select元素保存在变量中并执行以下操作:
function isValueInSelect($select, data_value){
return $($select).children('option').map(function(index, opt){
return opt.value;
}).get().includes(data_value);
}