2017-04-12 280 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>