[英]How to avoid adding same image multiple times to the div using jquery?
我在jquery中工作。 我編寫了一個腳本,該腳本將圖像從第一div添加到第二div。 但是,我不希望有可能兩次添加相同的圖像。
這是第一格的代碼
<div><span class="span1">
<img width="30" hieght="30" name="productimage" src="http://panther:805/Computers.jpg"></span>
<span class="span1">Black_xxl_Slim</span>
<span class="span1">1</span>
<a class="pull-right" href="#"><i onclick="Add(this)" class="icon-plus"></i></a>
</div>
這是第二個div的代碼:
<div class="span6" id="separat">
<ul class="thumbnails pre-scrollable" id="productbundles">
</ul>
</div>
這是我的jQuery
function Add(obj) {
var img = $(obj).closest('div').find('img').first();
var image_src = $(img).attr('src');
var newobj = $('<li class="span2" id="bunle' + id++ + '"><a href="javascript: void(0)"><img hieght=30 width=30 src="' + image_src + '" /></a><h5>'+"Name:" + name + '</h5><span id="pric' + id + '"><b>'+ "Price:"+ price + '</b></span>');
$('#productbundles').append(newobj);
}
添加div效果很好,但是允許將同一項目添加兩次。 我該如何阻止這種情況的發生? 在此先感謝您的幫助。
您必須具有已經存在或已添加的圖像列表,以免再次添加它們。 只需建立一個像這樣的列表:
var added_images = [];
並使用以下簡單方法檢查列表中的圖像是否存在:
if (added_images.indexOf(src)) {
// image already exists
} else {
// add the image to the list
added_images.push(src);
// and DOM...
}
if(!$("#productbundles img[src$='" + image_src + "'").length)
{
var newobj = $('<li class="span2" id="bunle' + id++ + '"><a href="javascript: void(0)"><img hieght=30 width=30 src="' + image_src + '" /></a><h5>'+"Name:" + name + '</h5><span id="pric' + id + '"><b>'+ "Price:"+ price + '</b></span>');
$('#productbundles').append(newobj);
}
如果您有完整的src路徑,請嘗試刪除$。
有很多方法可以執行此操作...您可以將類添加到已添加的<img>
中,然后使用hasClass
檢查hasClass
。
我這樣做的方式是..創建數組..並將src
推入數組並檢查src
是否存在於數組中
function Add(obj) {
var addedImagesArray=[];
var img = $(obj).closest('div').find('img').first();
var image_src = $(img).attr('src');
var newobj = $('<li class="span2" id="bunle' + id++ + '"><a href="javascript: void(0)"><img hieght=30 width=30 src="' + image_src + '" /></a><h5>'+"Name:" + name + '</h5><span id="pric' + id + '"><b>'+ "Price:"+ price + '</b></span>');
if (addedImagesArray.indexOf(image_src)) {
alert("Image Already Added");//src present in the array so do nothing or show an alert..
} else{
$('#productbundles').append(newobj); //append the image
addedImagesArray.push(image_src); ///add src to array
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.