如何在追加后检查元素是否存在?

时间:2016-09-19 18:59:23

标签: jquery append

以下脚本应该附加一个元素。我首先检查元素是否存在,如果不是我创建它并追加它。问题是,由于某种原因,检查似乎不起作用,它一直在反复创建元素......

问题:如何在追加后检查是否存在元素?

我的jsfiddle:

https://jsfiddle.net/mr54fbrL/

$(document).on("click", ".multilevel p.level", function(e) {

    var box = $(this).next(".itemMenuBox"); // box you want to interact with

    // if box does not exist, add it!
    if( !box.length ) {
        alert('not found, add it!');

        var box = $("<div></div>")
            .attr("class", 'itemMenuBox').text('new box')
            .appendTo($(this));
    } else {
        alert('found box');
    }
});

1 个答案:

答案 0 :(得分:1)

使用此Js:

$(document).on("click", ".multilevel p.level", function(e) {
        if($(this).find('div').hasClass('itemMenuBox')){
          alert('found box');
        }else{
              alert('not found, add it!'); 
             var box = $("<div></div>")
                .attr("class", 'itemMenuBox').text('new box')
                .appendTo($(this));
         }      
    });