簡體   English   中英

點擊鏈接刪除Div

[英]Remove Div on link click

我正在執行一個代碼,當單擊它的內部鏈接(“刪除”)時,我想刪除一個div。 我知道這個問題可能會重復,並且我嘗試了很多方法但沒有用。 我不知道這是什么問題。

這是我的HTML渲染代碼:

<div id="ViewRows">
    <br>
    <div class="ViewRow"> NOS: FA Comment: finance
        <a class="deleteViewRow" href="#">Delete</a>
    <br>
    </div>
    <div class="ViewRow">
       NOS: TPA Comment: Assistance
       <a class="deleteViewRow" href="#">Delete</a>
       <br>
    </div>
</div>

這是我刪除該div的javascript代碼。

$("a.deleteViewRow").live("click", function () {
   $(this).parents("div.ViewRow:first").remove();
   return false;
});

我也嘗試過以下javascript:

$("#ViewRows").on("click", "a.deleteViewRow", function () {
    $(this).closest("div.ViewRow").andSelf().remove();
    return false;
});

我在另一頁上嘗試了相同的代碼。 它正在工作,但是當我在另一頁中應用相同的邏輯時。 沒用 我知道你們都是對的,但我不知道出什么問題。 在螢火蟲中,它甚至都沒有進入功能。

這應該工作:

$("#ViewRows").on("click", "a.deleteViewRow", function (e) {
    // prevent browser from following link
    e.preventDefault();
    // ".andSelf()" can be skipped - once the parent div is removed, the link gets removed as well
    $(this).closest("div.ViewRow").remove();
});

這個簡單而有效的代碼可以正常工作: http : //jsfiddle.net/L2CsH/

$("#ViewRows").on("click", "a.deleteViewRow", function () {
    $(this).parent().remove();
});

您需要阻止鏈接的默認操作。 event.preventDefault()

$("#ViewRows").on("click", "a.deleteViewRow", function (e) {
    e.preventDefault();
    $(this).closest("div.ViewRow").remove(); //.andSelf() is not needed here. 
    //return false;
});

演示: 刪除Div JSFiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM