0

简而言之:

我有一个链接,单击将新 div 插入列表的链接。每个 div 都包含一个删除该 div 的链接。

所以,在工作的过程中,它看起来像这样:

<div id="list">
   <div id="item"><a href="#" id="remove_item">Remove</a></div>
   <div id="item"><a href="#" id="remove_item">Remove</a></div>
</div>

至于我有的点击处理程序

$("#remove_item").live 'click', (e) ->
    $(this).parent().remove()
    $(this).die()  # Unbind

现在,我的问题是这个处理程序的奇怪行为。如果我点击最后插入的 DIV 的链接,它会被正确删除,但如果我点击第一个 - 除了它被删除之外,它还会删除其中的每一个,恰好站在它后面. 因此,单击第一个,基本上会删除所有内容。

而且我只需要删除当前的,显然!:)

而且我不知道为什么解除绑定不起作用。不知道是不是和多次开火有关。:(

有人可以帮我解决这个问题吗?

4

3 回答 3

1

This should be a comment, but not enough points yet.

First of all, consider using .on() and .off as .live() is deprecated.

I can't reproduce your problem, your piece of code works for me here, probably something wrong with multiple binding and unbinding, as you mention. Maybe a little bit more of code would help.

Furthermore, you shouldn't use the same id. IDs should be unique for each element, better have a class="remove_item" and a unique id for each div.

于 2012-11-23T14:36:07.803 回答
1

DOM 元素的 ID 必须是唯一的。

你很可能只需要改变这个:

<div id="list">
   <div id="item"><a href="#" id="remove_item">Remove</a></div>
   <div id="item"><a href="#" id="remove_item">Remove</a></div>
</div>

对此:

<div id="list">
   <div class="item"><a href="#" class="remove_item">Remove</a></div>
   <div class="item"><a href="#" class="remove_item">Remove</a></div>
</div>

随着相关的 CoffeeScript 更改为:

$(".remove_item").live 'click', (e) ->
    $(this).parent().remove()

另外,我很确定你不需要打电话$(this).die(),因为你仍然希望其他 DIV 是可删除的。

于 2012-11-23T17:25:26.430 回答
0

好的。我不知道问题出在哪里,但是在我重新排列了一些 HTML 布局后,问题就解决了。而且我还是不太明白其中的原因。嗯,随便。感谢所有试图提供帮助的人!:)

于 2012-11-26T07:49:16.247 回答