我有类似这样的东西:
if (result.Indicator == 1) {
$('#IndicatorImgDiv').append($('<img />').attr("src", "/Content/images/reddot.png"));
}
现在,当我点击按钮时,它会追加一个红点的图像,但是当我再次点击该按钮时,它会再次追加。我只希望在我点击按钮时出现一次。如何检查已经存在或不存在的追加元素?
我有类似这样的东西:
if (result.Indicator == 1) {
$('#IndicatorImgDiv').append($('<img />').attr("src", "/Content/images/reddot.png"));
}
现在,当我点击按钮时,它会追加一个红点的图像,但是当我再次点击该按钮时,它会再次追加。我只希望在我点击按钮时出现一次。如何检查已经存在或不存在的追加元素?
只需做以下操作:
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"));
}
});
只需要改变:
$('#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"));
if($('img').length >= 1){
alert('element exist');
}