Le scénario est que j’ai deux div
s: l’un est l’endroit où je sélectionne des éléments ( divResults
) et passe au div suivant ( divSelectedContacts
). Lorsque je le sélectionne, je coche une coche. Ce que je veux faire, c’est que lorsque je le sélectionne à nouveau, je souhaite supprimer la coche et également supprimer l’élément de divSelectedContacts
.
Voici le code:
$("#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 } });
Je ne sais pas comment sélectionner la première span
dans un li
utilisant $(this)
. Toute aide est très appréciée.
Plusieurs façons:
$(this).find('span:first'); $(this).find(':first-child'); $(this).find('span').eq(0);
Notez qu’il n’est pas nécessaire d’utiliser $(deleteElement)
car deleteElement
est déjà un object jQuery. Donc, vous pouvez le faire comme ceci:
$(this).find('span:first').remove();
Pour obtenir le premier enfant de $(this)
utilisez ceci:
$(this).find(":first-child");
ou vous pouvez simplement tout jeter dans le sélecteur …
$('span:first', this);