且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用JQuery删除元素

更新时间:2023-12-05 18:46:28

首先,我建议在hover()事件上动态添加和删除元素可能会出现问题.通常的解决方案是显示/隐藏它们.它的性能也要好得多.

Well, firstly I would suggest that dynamically adding and removing elements on a hover() event could be problematic. The usual solution is to show/hide them as appropriate. It's far more performant too.

所以:

<div class="item">
  <p>Some content</p>
  <a class="close" href="#">X</a>
</div>

div.item a.close { display: none; }

$("div.item").hover(function() {
  $("a.close", this).fadeIn();
}, function() {
  $("a.close", this).fadeOut();
});
$("a.close").click(function() {
  $(this).parents("div.item:first").remove();
  return false;
});

现在,您可以通过将链接动态添加到DOM来做到这一点,但我建议您不要这样做.但是,如果这样做,请使用 live() 进行事件处理:

Now you can do this by dynamically adding the link to the DOM but I would advise against it. If you do however, use live() for the event handling:

$("a.close").live("click", function() {
  $(this).parents("div.item:first").remove();
});