删除具有相同类的现有兄弟,但不是这个

时间:2017-05-31 18:31:17

标签: jquery

<div class="slides">
 <img class="item-1 cardone" src="images/cardone.jpg"/>
 <img class="item-2 cardtwo" src="images/cardtwo.jpg"/>
 <img class="item-3 cardthree" src="images/cardthree.jpg"/>
 <img class="item-4 cardfour" src="images/cardfour.jpg"/>
 <img class="item-5 cardfive" src="images/cardfive.jpg"/>
 </div>

<img class="cardone" src="images/cardone.jpg"/><!-- gets added to slides on click, existing image with same class removed at the same time-->

$('.cardone').click(function(){
    var newSrc = $(this).attr('class');
    $(this).insertAfter($('.slides img:nth-child(2)')).addClass('item-3');
    $('.slides img').not(this).removeClass(newSrc);
}); 

当点击cardone时,它会被添加到幻灯片中,尝试用相同的类名替换现有图像。我得到的最远的是删除类而不是图像本身。

1 个答案:

答案 0 :(得分:1)

你可以这样做: -

 $("."+newSrc+"").not(this).remove();

实施例: -

&#13;
&#13;
$('.cardone').click(function(){
    var newSrc = $(this).attr('class');
    $("."+newSrc+"").not(this).remove();
    $(this).insertAfter($('.slides img:nth-child(2)')).addClass('item-3');
    
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slides">
 <img class="item-1 cardone" src="images/cardone.jpg"/>
 <img class="item-2 cardtwo" src="images/cardtwo.jpg"/>
 <img class="item-3 cardthree" src="images/cardthree.jpg"/>
 <img class="item-4 cardfour" src="images/cardfour.jpg"/>
 <img class="item-5 cardfive" src="images/cardfive.jpg"/>
 </div>

<img class="cardone" src="images/cardone.jpg"/> // gets added to slides on click, existing image with same class removed at the same time.
&#13;
&#13;
&#13;