【问题标题】:How can I check if append element already exists? [duplicate]如何检查附加元素是否已存在? [复制]
【发布时间】:2015-01-24 06:54:27
【问题描述】:

我有这样的事情:

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

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

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    只做下一步:

    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"));
             }
        });
    

    Here the JSFiddle!

    【讨论】:

    • 已编辑,感谢@DavidThomas!
    • 谢谢,您的解决方案最终对我来说是最好的!我只是将 if 语句更改为包含以下内容: ($("#IndicatorImgDiv img").length == 0
    • @WinnerCrespo 你也可以指出这是 jQuery 而不是 Vanilla JS
    【解决方案2】:

    只是改变:

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

    【讨论】:

      【解决方案3】:

      试试下面的代码。

      if($('img').length >= 1){
          alert('element exist');
      }
      

      【讨论】:

        猜你喜欢
        • 2020-10-02
        • 2011-09-25
        • 2021-11-18
        • 1970-01-01
        • 2011-06-18
        • 2017-12-30
        • 2018-01-31
        • 2011-06-15
        相关资源
        最近更新 更多