JQUERY each(), determining the # of matches so you can only act on the last one
When using JQUERY.each(), what is the way to obtain the value of matched items. I'd like to wrap 开发者_开发问答an IF inside the each() to only act on the last match. thx
That seems wasteful. Instead, just select the last item and act on it. E.g.:
$("td:last").hide();
$("p:last").hide();
The .each() method tells you which index item you are currently working with.
$.each(myItems, function(index, value) {
if(index == myItems.length-1)
doStuff(value);
});
It might be easier to just index the last item like so:
doStuff(myItems[myItems.length-1]);
instead of using each you can use :last
if you only want to get the last item of your DOM elements for example
<ul class="myUls">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
in you script, you can say
var last = $('.myUls li:last');
the DOM of the last would be the <li>three</li>
moreover if you want to select an index of an array of DOM element you can use :eq() say for example above you want to select the DOM <li>two</li>
you can do.
var two = $('.myUls li:eq(1)');
that will get you the two as <li>two</li>
As BrunoLM mentions, you should probably just use the :last
selector.
If you do want to know the number of matches for whatever other reason, you can use .size()
, or .length
e.g.
$("b").each(function(i) {
if (i == $("b").size() - 1) {
// do stuff
}
});
The :last
selector. In general though, if you want to know the position of the element you're iterating over with .each()
it gets passed to the callback.
$('.selector').each(function(index, elem) {
//index gets the position of the current elem
});
精彩评论