Is it possible to only select every 2nd element with the .each() function? If not, what alte开发者_开发问答rnatives are there?
You can use the :odd selector:
$("yourSelector:odd").each(function() {
// Will be called on every second element.
});
This might help:
$('li').each(function(index) {
if(index%2)
alert(index + ': ' + $(this).text());
});
You can use :nth-child() selector.
$("selector:nth-child(2)")
If you want to fetch particular element/node or tag in loop for e.g.
<p class="weekday" data-today="monday">Monday</p>
<p class="weekday" data-today="tuesday">Tuesday</p>
<p class="weekday" data-today="wednesday">Wednesday</p>
<p class="weekday" data-today="thursday">Thursday</p>
So, from above code loop is executed and we want particular field to select for that we have to use jQuery selection that can select only expecting element from above loop so, code will be
$('.weekdays:eq(n)');
e.g.
$('.weekdays:eq(0)');
as well as by other method
$('.weekday').find('p').first('.weekdays').next()/last()/prev();
but first method is more efficient when HTML <tag>
has unique class name.
NOTE:Second method is use when their is no class name in target element or node.
for more follow https://api.jquery.com/eq/
精彩评论