使用JQuery删除元素 [英] Remove element with JQuery

查看:74
本文介绍了使用JQuery删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用以下代码在翻转时将X链接附加到每个元素.

I'm currently using the following code to append a X link to each element on rollover.

$(".item").hover(function() {
    var id = $(this).attr("id");

    var roll = $('<a class="close" href="#">X</a>').hide();

    roll.prependTo($(this)).fadeIn(0);
}, function() {
    $(this).find("a:first").fadeOut(0, function() {
        $(this).remove()
    });
});

我无法编码的功能是当按下此X链接时,它会删除当前所在的父div.

What I am unable to code up is the ability for when this X link is pressed, it removes the parent div it is currently in.

在此方面,爱人会帮忙吗?)

Would love help on this :)

推荐答案

首先,我建议在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();
});

这篇关于使用JQuery删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆