我有这样的事情:
if (result.Indicator == 1) {
$('#IndicatorImgDiv').append($('<img />').attr("src", "/Content/images/reddot.png"));
}
现在,当我单击一个按钮时,它会追加一个红色点的图像,但当我再次单击一个按钮时,它会再次追加它。我只想让它出现一次,当我点击一个按钮。如何检查附加的元素是否已经存在?
发布于 2014-11-26 03:39:12
只需做下一个:
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!
发布于 2014-11-26 03:28:51
只要改变:
$('#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"));
发布于 2014-11-26 03:25:35
试试下面的代码。
if($('img').length >= 1){
alert('element exist');
}
https://stackoverflow.com/questions/27140796
复制相似问题