2013-05-31 96 views
1

我試圖從單擊頁面中的href時,從頁面中刪除父div。可以有多個相同的div,或者我只是使用類名。我試圖使用$(this).remove();但只能刪除刪除按鈕。我已經看過父母的屬性,但我不確定我完全理解這是如何工作的。刪除單擊元素內部的div

這是我有:

<script>   
$(".delete-button").click(function(){ 
    $(this).remove();   
}); 
</script> 


<div class="bottomsurgicalhistory"> 

    "Div Content is Here" 
    <li class="delete"><a href="#" class="delete-button"></a></li> 
</div> 

<div class="bottomsurgicalhistory"> 

    "Div Content is Here" 
    <li class="delete"><a href="#" class="delete-button"></a></li> 
</div> 

所有幫助表示讚賞!

+1

嘗試'$(this).closest(「。bottomsurgicalhistory」)。remove();'。在你的HTML中,你可以很容易地使用'$(this).parent()。remove();'。這裏是'nearest()'的文檔:http://api.jquery.com/closest/。當你不確定元素是如何嵌套的時候,它是很好/可靠的,但是你知道一些祖先會匹配選擇器並且可以工作 – Ian

+0

注意LI元素應該在UL裏面,我猜這只是僞代碼,但仍然! – adeneo

回答

3

如果腳本標記出現在元素之前,那麼您需要一個dom ready函數,並且在使用散列作爲href時防止默認滾動到頂部通常是個好主意。當點擊刪除按鈕,使用closest()發現MATHES的bottomsurgicalhistory類的最近父:

$(function() { 
    $(".delete-button").on('click', function(e){ 
     e.preventDefault(); 
     $(this).closest('.bottomsurgicalhistory').remove();   
    }); 
}); 
+0

謝謝,這個作品完美! –

+0

@KevinWeber - 不客氣! – adeneo

2

只需更換你的下面的代碼:

$(this).remove(); 

爲這一個:

$(this).parent().remove(); 
1

嘗試這個。

$(this).parent().remove();