Grab only 2 items from Jquery Loop
Here is my Jquery
$th.each(function(idx) {
var notSelected = $(this).text();
if ((notSelected.indexOf(to) != -1) || (notSelected.indexOf(from) != -1)) {
if (idx < 10)
{
$(this).show();
// and show its corresponding td
$td.eq(idx).show();
}
}
});
It is part of a tableFilter type function for a HTML table. Howev开发者_Go百科er I want it to only display only 2 of the results. I tried instantiating some kind of index counter but I was unsuccessful. Any help or thoughts would be appreciated.
var index = 0;
$th.each(function(idx) {
var notSelected = $(this).text();
if ((notSelected.indexOf(to) != -1) || (notSelected.indexOf(from) != -1)) {
if (idx < 10 && index < 2)
{
$(this).show();
// and show its corresponding td
$td.eq(idx).show();
index = index + 1;
}
}
});
This is more efficient than the accepted answer and won't pollute your namespace.
(function(index){
$th.each(function(idx) {
if(idx < 10){
var self = $(this),
notSelected = self.text();
if ( notSelected.indexOf(to) > -1 || notSelected.indexOf(from) > -1 )
self.show();
// and show its corresponding td
$td.eq(idx).show();
if(++index===2){
//break the loop
return false;
}
}
}
});
}(0));
精彩评论