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

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

这是代码:

 $("#divResults li").click(function() { if ($(this).find('span').size() == 1) { var copyElement = $(this).children().clone(); $(this).children().prepend(""); $("#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 。 任何帮助深表感谢。

几种方式:

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

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

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

要获得$(this)第一个孩子 ,请使用:

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

或者你可以将它全部扔进选择器……

 $('span:first', this);