点击链接删除Div

Remove Div on link click

本文关键字:Div 删除 链接      更新时间:2023-09-26

我正在做一个代码,我想删除一个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>

这是我的javascript代码删除该div。

$("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;
});

我在另一个页面上尝试了相同的代码。它是工作的,但当我在另一个页面应用相同的逻辑。这行不通。我知道你们都是对的,但我不知道有什么问题。在firebug中,它甚至不会进入函数

应该可以:

$("#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;
});

演示:Remove Div JSFiddle