如何使用 jQuery 独特地向 select 中添加选项。
如何使用 jQuery 独特地向 select 中添加选项。
我在一个
中有很多独特的选项。只有当新选项是唯一的且不存在于现有选项中时,我才需要添加一个新选项。
我如何使用 jQuery 查找给定的 option
是否已存在于给定的 select
中?
例如:
- 新有效选项:梨子
- 新无效选项:苹果
admin 更改状态以发布 2023年5月22日
if (!$("#combobox option[value='Apple']").length) // Add it
使其可重用可以是:
if (!$("#combobox option[value='" + value + "']").length) // Add it
不区分大小写:
var isExist = !$('#combobox option').filter(function() { return $(this).attr('value').toLowerCase() === value.toLowerCase(); }).length;
完整代码:(演示)
$('#txt').change(function() { var value = this.value; var isExist = !!$('#combobox option').filter(function() { return $(this).attr('value').toLowerCase() === value.toLowerCase(); }).length; if (!isExist) { console.log(this.value + ' is a new value!'); $('