如何删除元素的第一个孩子,但在Jquery中被$(this)引用? [英] How to delete the first child of an element but referenced by $(this) in Jquery?

查看:205
本文介绍了如何删除元素的第一个孩子,但在Jquery中被$(this)引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是代码:

$("#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
    }
});

我不知道如何使用$(this)li中选择第一个span.非常感谢您的帮助.

I don't know how to select the first span in a li using $(this). Any help is much appreciated.

推荐答案

几种方法:

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

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

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

请注意,您无需使用$(deleteElement),因为deleteElement已经是jQuery对象.因此,您可以这样做:

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

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

这篇关于如何删除元素的第一个孩子,但在Jquery中被$(this)引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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