如果不存在,jQuery追加 [英] jQuery append if doesn't exist

查看:64
本文介绍了如果不存在,jQuery追加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想附加一个 div 只有它还没有。我正在尝试这个但它不起作用:

I would like to append a div only if it's not already there. 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();
    }
});

如果我删除第二个if子句,每当我选择一个通过的选项时它会被追加第一个if子句

And if I remove the second if-clause, it gets appended every time I select an option which passes first if-clause

这是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,如下所示:

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:

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

这篇关于如果不存在,jQuery追加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆