在添加到html页面之前验证元素是否存在

Verifiy if element exists before add to html page

本文关键字:验证 元素 是否 存在 添加 html      更新时间:2023-09-26

在我当前的春季项目中,我有一些<select>字段,其中的选项是通过以下jquery代码添加的:

function load_options(target, lista) {
    $.ajax({
        type: 'GET',
        url: lista
    }).done(function(data){
        var json = jQuery.parseJSON( data );
        $.each(json.item, function(index, item) {
            var option = $('<option class="form-control" value="'+item.id+'">'+item.nome+'</option>');
            if(<<condition>>)
                target.append(option);
        });
    });
}

我正在寻找一个<<condition>>,在那里我可以验证存储在变量中的选项是否存在,然后将其添加到选择中。

有人知道怎么检查这个吗?

jQuery构造函数(这是您传递选择器的地方)返回一个数组,因此,如果元素存在,该数组的长度属性为1(或更多)。你可以在此基础上写条件

我会这样做,但我对其他解决方案更感兴趣:

...
var json = jQuery.parseJSON( data );
var opt = [];
...
if(!opt[item.nome])
  target.append(option);
opt[item.nome]= true;
...