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

21

我有类似这样的东西:

if (result.Indicator == 1) {
    $('#IndicatorImgDiv').append($('<img />').attr("src", "/Content/images/reddot.png"));
}

现在,当我点击按钮时,它会追加一个红点的图像,但是当我再次点击该按钮时,它会再次追加。我只希望在我点击按钮时出现一次。如何检查已经存在或不存在的追加元素?

3个回答

15

只需做以下操作:

Html 代码

    <input id="addImage" type="button" value="Add image"/>
    <div id="IndicatorImgDiv">
    </div>

Javascript 代码

    $("#addImage").click(function(){
         if($("#IndicatorImgDiv img").length == 0){
             $('#IndicatorImgDiv').append($('<img />').attr("src", "http://www.thepointless.com/images/reddot.jpg"));
         }
    });

这里是 JSFiddle!


谢谢,你的解决方案最终对我最有效!我只是更改了if语句以包括这个:($("#IndicatorImgDiv img").length == 0 - Kala J
@WinnerCrespo 你还可以指出这是jQuery而不是纯JS。 - wbq

1

只需要改变:

$('#IndicatorImgDiv').append($('<img />').attr("src", "/Content/images/reddot.png"));

收件人:

$('#IndicatorImgDiv').find('img[src$="reddot.png"]').length ||
    $('#IndicatorImgDiv').append($('<img />').attr("src", "/Content/images/reddot.png"));

0
尝试下面的代码。
if($('img').length >= 1){
    alert('element exist');
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接