如果不存在,则追加 jQuery 追加



我想仅在div不存在时才附加它。我正在尝试这个,但它不起作用:

$('#method_id').on('change', function (e) {
    if ($(this).find("option:selected").data('method-column-id') != 1) {
        if ($('#column_message').next('div').length)
            $('#column_message')
                    .append('<div id="warning_message" class="alert alert-danger"><strong>Warning!</strong> Installed column and method do not match</div>');
    } else {
        $('.form-group').find('#column_message>.alert').remove();
    }
});

如果我删除第二个 if 子句,每次我选择传递第一个 if 子句的选项时都会附加它

这是 HTML

<!-- Warning message -->
<div class="form-group">
    <label for="group" class="col-md-2 control-label"></label>
    <div id="column_message" class="col-md-6">
    </div>
</div>

为了检查一个元素是否存在,你需要找到一个只与该元素匹配的选择器,并检查 jQuery 对象的长度是否等于 0,如下所示:

if ($('#unique-selector').length === 0) {
    // code to run if it isn't there
}
else {
    // code to run if it is there
}

当您在div 后附加 id 时,您可以搜索该div 是否存在通过调用 :

if($("#warning_message").length > 0 ){
   $('.form-group').find('#column_message>.alert').remove();
}else{
   $('#column_message').append('<div id="warning_message" class="alert alert-danger"><strong>Warning!</strong> Installed column and method do not match</div>');
}

但是,如果您想拥有更多的警报div,则可以搜索"alert"类左右。

没有id的另一种方法(可能更好(是使用子(( 方法

内部 if 应该是if ($('#column_message').next('div').length===0)if(!$('#column_message').next('div').length)

最新更新