2013-11-24 23 views
0

我正在使用下面的函數來篩選基於輸入字段,它工作正常的表。jQuery:使用變量td:eq

目前這是指一個固定的列索引,我說「'td:eq(3)'」。

如何在此處引用我的變量「colIndex」而不是使用固定列索引? 另外,有沒有一種方法可以基於我的第一行代碼獲取當前表的ID,以便我不必引用下面的表類(「myTable」)?

我的代碼(工作):

$('.myClass').on('keyup', function() { 
    var colIndex = $(this).closest('th').index(); 
    var regex = new RegExp($(this).val().toLowerCase(), "i"); 
    $('.myTable').find('tr:gt(1)').each(function() { 
     if ($(this).find('td:eq(3)').text().match(regex) == null) { 
      $(this).hide(); 
     } else { 
      $(this).show(); 
     } 
    }); 
}); 

與此的任何幫助,蒂姆非常感謝。

回答

1

你可以只串連成是這樣選擇的字符串:

$(this).find('td:eq(' + colIndex + ')') 

給你

$('.myClass').on('keyup', function() { 
    var colIndex = $(this).closest('th').index(); 
    var regex = new RegExp($(this).val().toLowerCase(), "i"); 

    $('.myTable').find('tr:gt(1)').each(function() { 
     if ($(this).find('td:eq(' + colIndex + ')').text().match(regex) == null) { 
      $(this).hide(); 
     } else { 
      $(this).show(); 
     } 
    }); 
}); 

它似乎更容易做這樣的事情:

$('.myClass').on('keyup', function() { 
    var idx = $(this).closest('th').index(), 
     val = this.value.toLowerCase(); 

    $('.myTable tr:gt(1)').css('display', function() { 
     return $('td', this).eq(idx).text().toLowerCase() == val ? 'block' : 'hide'; 
    }); 
}); 
+0

非常感謝 - 這是完美的。我會試試這個建議。 – user2571510

1

你需要使用字符串連接

$('.myClass').on('keyup', function() { 
    var colIndex = $(this).closest('th').index(); 
    var regex = new RegExp($(this).val().toLowerCase(), "i"); 
    $('.myTable').find('tr:gt(1)').each(function() { 
     if ($(this).find('td:eq(' + colIndex + ')').text().match(regex) == null) { 
      $(this).hide(); 
     } else { 
      $(this).show(); 
     } 
    }); 
}); 

或我的首選方法是使用.eq()

$('.myClass').on('keyup', function() { 
    var colIndex = $(this).closest('th').index(); 
    var regex = new RegExp($(this).val().toLowerCase(), "i"); 
    $('.myTable').find('tr:gt(1)').each(function() { 
     if ($(this).find('td').eq(colIndex).text().match(regex) == null) { 
      $(this).hide(); 
     } else { 
      $(this).show(); 
     } 
    }); 
}); 

一些變化,你可以嘗試是

var $table = $('.myTable'); 
$('.myClass').on('keyup', function() { 
    var colIndex = $(this).closest('th').index(); 
    var regex = new RegExp($(this).val().toLowerCase(), "i"); 
    $table.find('tr').slice(1).each(function() { 
     $(this).toggle(regex.test($(this).find('td').eq(colIndex).text())); 
    }); 
}); 
+0

非常感謝 - 我也會試試這個。 – user2571510

0

沒有可用另一種方式來做到這一點,那就是使用nth-child選擇。但是:eq:nth-selector之間有一個小的差異。即:eq更喜歡下限爲0,但同時:nth-child更喜歡下限爲1

$('.myClass').on('keyup', function() { 
    var colIndex = $(this).closest('th').index(); 
    var regex = new RegExp($(this).val().toLowerCase(), "i"); 
    $('.myTable').find('tr:gt(1)').each(function() { 
     if ($(this).find('td:nth-child(' + (colIndex + 1) + ')').text().match(regex) == null) { 
      $(this).hide(); 
     } else { 
      $(this).show(); 
     } 
    }); 
});