2013-01-09 53 views
0

我正在jquery中工作。 我已经写了一个脚本,从第一个div添加图像到第二个div。 但是,我不希望它有可能两次添加相同的图像。如何避免使用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作品很好,但它允许相同的物品被添加两次。 我该如何阻止这种情况发生? 在此先感谢您的帮助。

回答

0

很多方法可以做到这一点......你可以添加一个类到<img>已被追加并检查该类别..使用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 
    } 
} 
+0

thnk u代表亩回复让我尝试这 –

+0

thinks bipen其工作很好的代码非常感谢 –

+0

欢迎...快乐编码 – bipen

0

您必须拥有已经存在或已添加的图像列表,以避免再次添加它们。只需建立一个像列表:

var added_images = []; 

,并检查用一个简单的列表内图像存在:

if (added_images.indexOf(src)) { 
    // image already exists 
    } else { 
     // add the image to the list 
     added_images.push(src); 
     // and DOM... 
    } 
0
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的完整路径

,尝试用去除$。

相关问题