如何使用 jQuery 独特地向 select 中添加选项。

13 浏览
0 Comments

如何使用 jQuery 独特地向 select 中添加选项。

我在一个 中有很多独特的选项。只有当新选项是唯一的且不存在于现有选项中时,我才需要添加一个新选项。

我如何使用 jQuery 查找给定的 option 是否已存在于给定的 select 中?

例如:


  • 新有效选项:梨子
  • 新无效选项:苹果
admin 更改状态以发布 2023年5月22日
0
0 Comments

我猜你想通过“value”进行搜索而不是通过文本内容进行搜索。 在你的例子中,它们总是相同的,但可能它们并不总是相同的....

var toAdd = 'Apricot',
    combobox = $('#combobox');
if (!combobox.find('option[value="' + toAdd + '"]').length) {
    combobox.append('');
}

0
0 Comments

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!');
        $('

实时演示

0