This question already has an answer here:
这个问题在这里已有答案:
- Is there an “exists” function for jQuery? 35 answers
- jQuery是否存在“存在”功能? 35个答案
I have something like this:
我有这样的事情:
if (result.Indicator == 1) {
$('#IndicatorImgDiv').append($('<img />').attr("src", "/Content/images/reddot.png"));
}
Now, this appends an image of a red dot when I click on a button but when I click on a button again, it appends it again. I just want it to appear once when I click on a button. How can I check if the appended element already exists or not?
现在,当我点击一个按钮时,这会附加一个红点图像,但是当我再次点击一个按钮时,它会再次附加一个按钮。我只是希望它在我点击按钮时出现一次。如何检查附加元素是否已存在?
3 个解决方案
#1
11
Just do the next:
做下一个:
Html code
Html代码
<input id="addImage" type="button" value="Add image"/>
<div id="IndicatorImgDiv">
</div>
Javascript code
Javascript代码
$("#addImage").click(function(){
if($("#IndicatorImgDiv img").length == 0){
$('#IndicatorImgDiv').append($('<img />').attr("src", "http://www.thepointless.com/images/reddot.jpg"));
}
});
在这里JSFiddle!
#2
0
Just change:
只是改变:
$('#IndicatorImgDiv').append($('<img />').attr("src", "/Content/images/reddot.png"));
To:
至:
$('#IndicatorImgDiv').find('img[src$="reddot.png"]').length ||
$('#IndicatorImgDiv').append($('<img />').attr("src", "/Content/images/reddot.png"));
#3
0
Try the following code.
请尝试以下代码。
if($('img').length >= 1){
alert('element exist');
}
#1
11
Just do the next:
做下一个:
Html code
Html代码
<input id="addImage" type="button" value="Add image"/>
<div id="IndicatorImgDiv">
</div>
Javascript code
Javascript代码
$("#addImage").click(function(){
if($("#IndicatorImgDiv img").length == 0){
$('#IndicatorImgDiv').append($('<img />').attr("src", "http://www.thepointless.com/images/reddot.jpg"));
}
});
在这里JSFiddle!
#2
0
Just change:
只是改变:
$('#IndicatorImgDiv').append($('<img />').attr("src", "/Content/images/reddot.png"));
To:
至:
$('#IndicatorImgDiv').find('img[src$="reddot.png"]').length ||
$('#IndicatorImgDiv').append($('<img />').attr("src", "/Content/images/reddot.png"));
#3
0
Try the following code.
请尝试以下代码。
if($('img').length >= 1){
alert('element exist');
}