问题
I am trying to use jquery to specifically select a sibling a parent element that has the same . the code is like this:
HTML
<div class="cool-check-list">
<ul>
<li>
<label>
<span class="icon"></span> <!-- trying to select this -->
Awesome Label Name
</label>
<ul>
<li>
<label>
<span class="icon"></span> <!-- clicking this toggles the class of the above icon class -->
Awesome Label Name 2
</label>
</li>
</ul>
</li>
</ul>
</div>
JQUERY
$('.icon', '.cool-check-list').click( function(e){
$(this).parent('li label .icon').toggleClass('icon-alternate');
});
回答1:
Assuming you've already gotten a reference to the clicked span, you could do this:
$(this).closest("ul").siblings().find(".icon")
Where this
is the span
you clicked. closest
gets the nearest ancestor that matches the selector.
回答2:
You should tell us more precisely what you wanted to select and what you tried.
Anyway, you can use the parents() function of jquery, for instance :
$(".icon").parents("li")
will select every node li 'before' the class icon in the DOM.
Btw, take care of the difference between parents and parent - quoting the jquery documentation:
The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree.
来源:https://stackoverflow.com/questions/6455436/how-do-i-use-jquery-to-select-a-sibling-of-the-parent-element