2017-04-12 167 views
1

我想在鼠标悬停在元素上方时显示已经存在的div。 该元素具有与div匹配的ID。删除克隆的div(jQuery)

克隆和显示部分工作在悬停,但我坚持删除已克隆的元素。我看到另一个答案中提到的衣柜,但我可能使用它错了。

$('.referer').hover(function() { 
 
    var id = $(this).attr('id') 
 
    $('#reply_' + id).clone().appendTo(this); 
 
}, function() { 
 
    var id = $(this).attr('id') 
 
    $('#reply_' + id).closest(this).remove(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="reply_1"> 
 
First Post 
 
</div> 
 
<div id="reply_2"> 
 
Second Post 
 
</div> 
 
<div id="reply_3"> 
 
Third Post 
 
</div> 
 
<!--The id is the id of the quoted post--> 
 
<p> 
 
<span class="referer" id="1">Quoted Link (First Post)</span>

回答

2

你不需要在这种情况下closest()功能,但find()代替,如:

$(this).find('#reply_' + id).remove(); 

所以只是你查找'#reply_' + id当前元素this和删除内它。

希望这会有所帮助。

$('.referer').hover(function() { 
 
    var id = $(this).attr('id') 
 
    $('#reply_' + id).clone().appendTo(this); 
 
}, function() { 
 
    var id = $(this).attr('id') 
 
    $(this).find('#reply_' + id).remove(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="reply_1">First Post</div> 
 
<div id="reply_2">Second Post</div> 
 
<div id="reply_3">Third Post</div> 
 
<!--The id is the id of the quoted post--> 
 
<p> 
 
<span class="referer" id="1">Quoted Link (First Post)</span> 
 
<br> 
 
<span class="referer" id="2">Quoted Link (Second Post)</span> 
 
<br> 
 
<span class="referer" id="3">Quoted Link (Third Post)</span>