2010-04-07 40 views
13

該場景是我有兩個div s:一個是我選擇項目(divResults)的地方,它會轉到下一個div(divSelectedContacts)。當我選擇它時,我在它旁邊放置一個刻度線。我想要做的是當我再次選擇它時我想刪除刻度標記並從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。任何幫助深表感謝。

回答

26

幾種方法:

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

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

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

請注意,您不需要使用$(deleteElement)作爲deleteElement已經是一個jQuery對象。所以,你可以做這樣的:

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

太謝謝你了:-)。 deleteElement沒有發生在我身上。接得好。 – Raja 2010-04-07 13:58:35

5

爲了得到第一個孩子的$(this)使用本

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

,或者你可以只把它所有進入選擇...

$('span:first', this); 
+0

我喜歡它,很棒! – Gabe 2010-04-07 14:00:34

+0

甜,我喜歡這個實現。爲你+1。 – Raja 2010-04-07 14:05:29

相關問題