【发布时间】:2010-10-13 09:03:45
【问题描述】:
如何通过 JQuery 检查 select 中是否已存在选项?
我想动态地将选项添加到select中,所以我需要检查该选项是否已经存在以防止重复。
【问题讨论】:
标签: jquery
如何通过 JQuery 检查 select 中是否已存在选项?
我想动态地将选项添加到select中,所以我需要检查该选项是否已经存在以防止重复。
【问题讨论】:
标签: jquery
如果它已经存在,则计算结果为 true:
$("#yourSelect option[value='yourValue']").length > 0;
【讨论】:
另一种使用jQuery的方式:
var exists = false;
$('#yourSelect option').each(function(){
if (this.value == yourValue) {
exists = true;
}
});
【讨论】:
.length 可能会这样做。
if ( $("#your_select_id option[value=<enter_value_here>]").length == 0 ){
alert("option doesn't exist!");
}
【讨论】:
var exists = $("#yourSelect option")
.filter(function (i, o) { return o.value === yourValue; })
.length > 0;
这具有自动为您转义值的优点,这使得文本中的随机引号更容易处理。
【讨论】:
虽然大多数其他答案对我有用,但我使用了 .find():
if ($("#yourSelect").find('option[value="value"]').length === 0){
...
}
【讨论】:
不起作用,你必须这样做:
if ( $("#your_select_id option[value='enter_value_here']").length == 0 ){
alert("option doesn't exist!");
}
【讨论】:
这对我有帮助:
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 选择元素保存在一个变量中并这样做:
function isValueInSelect($select, data_value){
return $($select).children('option').map(function(index, opt){
return opt.value;
}).get().includes(data_value);
}
【讨论】: