如何删除元素的第一个子元素但在 Jquery 中被 $(this) 引用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2592891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:51:13  来源:igfitidea点击:

How to delete the first child of an element but referenced by $(this) in Jquery?

jqueryjquery-selectors

提问by Raja

The scenario is I have two divs: one is where I select items (divResults) and it goes to the next div (divSelectedContacts). When I select it I place a tick mark next to it. What I want to do is when I select it again I want to remove the tick mark and also remove the element from divSelectedContacts.

场景是我有两个divs:一个是我选择项目 ( divResults) 的地方,然后它转到下一个 div ( divSelectedContacts)。当我选择它时,我会在它旁边放置一个勾号。我想要做的是当我再次选择它时,我想删除刻度线并从divSelectedContacts.

Here is the code:

这是代码:

$("#divResults li").click(function()
{
    if ($(this).find('span').size() == 1)
    {
        var copyElement = $(this).children().clone();
        $(this).children().prepend("<span class='ui-icon ui-icon-check checked' style='float:left'></span>");
        $("#divSelectedContacts").append(copyElement);
    } else
    {
        var deleteElement = $(this).find('span'); //here is the problem how to find the first span and delete it
        $(deleteElement).remove();
        var copyElement = $(this).children().clone();//get the child element
        $("#divSelectedContacts").find(copyElement).remove(); //remove that element by finding it
    }
});

I don't know how to select the first spanin a liusing $(this). Any help is much appreciated.

我不知道如何spanliusing 中选择第一个$(this)。任何帮助深表感谢。

回答by Tatu Ulmanen

Several ways:

几种方式:

$(this).find('span:first');

$(this).find(':first-child');

$(this).find('span').eq(0);

Note that you don't need to use $(deleteElement)as deleteElementis already a jQuery object. So you can do it like this:

请注意,您不需要使用$(deleteElement)asdeleteElement已经是 jQuery 对象。所以你可以这样做:

$(this).find('span:first').remove();

回答by Gabe

To get the first childof $(this)use this:

为了得到第一个孩子$(this)使用:

$(this).find(":first-child");

回答by ryan j

or you could just throw it all into the selector...

或者你可以把它全部扔到选择器中......

$('span:first', this);