简体   繁体   English

如果不存在,jQuery追加

[英]jQuery append if doesn't exist

I would like to append a div only if it's not already there. 我想只在它不存在时附加一个div I am trying with this but it doesn't work: 我正在尝试这个但它不起作用:

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

And if I remove the second if-clause, it gets appended every time I select an option which passes first if-clause 如果我删除第二个if子句,每次选择传递第一个if子句的选项时都会附加它

Here is the HTML 这是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>

In order to check if an element exists, you need to find a selector that matches only that element and check if the length of the jQuery object is equal to 0 or not, like so: 为了检查元素是否存在,您需要找到仅匹配该元素的选择器,并检查jQuery对象的长度是否等于0,如下所示:

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

As you are appending div with id, you could just search if that div exists by calling : 当您使用id附加div时,您可以通过调用来搜索该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>');
}

But if you would like to have more divs of alert, you could just search for class "alert" or so. 但是如果你想拥有更多div警报,你可以只搜索“警报”等级。

Another way without id ( probably better ) would be to use children() method 没有id(可能更好)的另一种方法是使用children()方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM