如果不存在,jQuery追加

时间:2017-03-19 21:07:27

标签: javascript 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(); } }); 时才附加<!-- 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> 。我正在尝试这个但它不起作用:

$resultarr

如果我删除第二个if子句,每当我选择一个先传递if-clause的选项时它会被追加

这是HTML

idmeny

3 个答案:

答案 0 :(得分:10)

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

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

答案 1 :(得分:0)

当您使用id附加div时,您可以搜索该div是否存在 致电:

#!/bin/sh

## function to print error message and exit
fail () {
  echo "!!! $0: $1" >&2
  exit 1
}

## check script is being run from top-level source directory
test "$0" = "./00boot" || fail "must be run from top-level source directory"

## remove M4 cache files
rm -rf autom4te.cache/
rm -f aclocal.m4

# FIXME: autoreconf from Ubuntu 9.10 (and probably also from recent
# Debian versions) automatically run libtoolize with the --copy option
# therefore over writing the supplied libtool scripts with system
# version. This can lead to unexpected build failures therefore to work
# round this "feature" we set the LIBTOOLIZE enviroment variable to
# point to the the true executable which bypasses the running of
# libtoolize, this will not effect the vast majority of users and those
# it will effect will know how to run libtoolize, if required.

## run autoreconf
AUTORECONF=${AUTORECONF:-"autoreconf"}
echo "00boot: running ${AUTORECONF}"
LIBTOOLIZE=true ${AUTORECONF} || fail "${AUTORECONF} failed"

echo "
==================================================
00boot has been run successfully.
Now run './configure' with appropriate options
to configure LALSuite.
==================================================
"

但是如果你想要更多div警报,你可以只搜索课程&#34;警告&#34;左右。

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

答案 2 :(得分:0)

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