jQuery表列搜索过滤器 [英] jQuery table column search filter
问题描述
我正在尝试使用jquery在html表的特定列中搜索数据.我搜索了不同的答案,但找不到适合我的答案.
I'm trying to search for data in a specific column of an html table using jquery. I've searched for different answers but I can't find one that suits me.
表只是一个简单的表:
<table id="tabla">
<tr>
<th>TimeStamp</th>
<th>IP</th>
<th>Nombres</th>
<th>Descripción</th>
</tr>
</table>
我找到了一段代码,可以让您在整个表格中搜索数据:
I found a piece of code that allows you to search for data in the whole table:
var $rows = $('#tabla_servicios tr');
var $col_ip = $('#ip');
$('#buscar1').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
但是我想按列搜索.
这是我的第二种方法:
$('#buscar').click(function() {
var table = document.getElementById("tabla_servicios");
var sel_opt = document.getElementById("options");
var busqueda = $("#busqueda").prop("value");
var column_sel = 0;
if (sel_opt.value == "timestamp"){
//alert("opcion timestamp");
column_sel = 0;
}else if (sel_opt.value == "ip"){
//alert("opcion ip");
column_sel = 1;
}else if (sel_opt.value == "nombres"){
//alert("opcion nombres");
column_sel = 2;
}else if (sel_opt.value == "descripcion"){
//alert("opcion descripcion");
column_sel = 3;
}
var column_length = $('#tabla_servicios tr th').length;
//alert("column_length = "+column_length);
var row_length = $('#tabla_servicios tr').length;
for(row=1; row<row_length; row++){
var data=$('#tbody_tabla tr:eq('+row+') td:eq('+column_sel+')').text();
//alert("busqueda: "+busqueda+" data: "+data);
if(busqueda == data){
$('#tbody_tabla tr:eq('+row+')').remove();
data.parent().css("font-size: 200%");
}
}
});
但是它无法正常工作,css代码不起作用,并且仅当我在if内添加警报时,才能删除该行.
But it doesn't work correctly, the css code doesn't work and for removing the row it works only when I add an alert inside the if.
推荐答案
您可以尝试以下操作:
HTML:
<table id="tabla">
<tbody id="tbody_tabla">
<tr>
----
</tr>
</tbody>
</table>
jQuery:
for(col=0;col<=column_length; col++){
for(row=0; row<=row_length; row++){
var data=$('#tbody_tabla tr:eq('+row+') td:eq('+col+')').text();
}
}
您还可以动态找到列数和行数
例如:column_length = $("#tbody_tabla tr:first td").length;
Also you can find the number of columns and number of rows dynamically
Ex: column_length = $("#tbody_tabla tr:first td").length;
这篇关于jQuery表列搜索过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!