jQuery selector inside the each() method

2019-02-05 02:06发布

问题:

Lets say that I have a HTML that looks like this:

<div class="aaa"><span>1</span></div>
<div class="aaa"><span>2</span></div>
<div class="aaa"><span>3</span></div>
<div class="aaa"><span>4</span></div>

With $('.aaa span') I can select all span elements.
With $('.aaa').each() I can iterate over the div elements.
My question is how to select the span in each div from inside the each function like:

$('.aaa').each(function(index, obj){
    x = selector_based_on_obj // x equal to the current div`s span
})

回答1:

easiest way is this, if you want all the elements

$('.aaa span');

jquery can nest selectors just like css can. also, if for some reason you need to loop

$('.aaa').each(function(){
    x = $(this).find('span');
});

that will set x as the elements as a jquery object.



回答2:

$(obj).find('span') should do the trick.



回答3:

$('.aaa').each(function() {
  var x = $('span', this);
});


回答4:

$('.aaa').each(function(index, obj){
    var x = $(this).find('span');
    $(x).doSomething();
})

or more prgramatically:

$('.aaa').each(function(index, obj){
    $(this).find('span').doSomething();
})


回答5:

If that's your actual markup, you can easily use the native property firstChild.

$('.aaa').each(function(){
    var x = this.firstChild
});

It is a widely supported property.