0

我正在编写一个代码,我想在单击其内部链接(“删除”)时删除一个 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;
});

我在另一个页面上尝试了相同的代码。它正在工作,但是当我在另一个页面中应用相同的逻辑时。它不工作。我知道你们都是对的,但我不知道有什么问题。在萤火虫它甚至没有进入功能。

4

3 回答 3

2

这应该有效:

$("#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();
});
于 2013-03-11T12:49:39.380 回答
1

这个简单而有效的代码工作正常:http: //jsfiddle.net/L2CsH/

$("#ViewRows").on("click", "a.deleteViewRow", function () {
    $(this).parent().remove();
});
于 2013-03-11T12:58:48.913 回答
0

您需要防止链接的默认操作。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

于 2013-03-11T12:48:07.353 回答