如何在同一页面中使用相同的javascript过滤器两次使用不同的表格?

时间:2018-03-02 14:59:10

标签: javascript jquery datatable

我想在同一页面上使用相同的javascript过滤器,但是有两个或三个不同的表和不同的输入字段。
以下是我用来过滤表格日期的脚本。<登记/> 如果有2个或更多表怎么办?

function filterFunction() {
  var input, filter, table, tr, td, i, totalViewable = 0;
  input = document.getElementById("event_date_range");
  filter = input.value.toUpperCase();
  table = document.getElementById("dateTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[1];
    tds = tr[i].getElementsByTagName("td")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
        totalViewable += parseFloat(tds.innerHTML);
        document.getElementById("total_amount_td").innerHTML = "$" + totalViewable.toFixed(2);
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}
  

表格 - dataTable
  输入字段 - event_date_range
  输出文本 - total_amount_td

1 个答案:

答案 0 :(得分:0)

tableinputtotal_amount_id作为参数传递给filterFunction

类似的东西:

function filterFunction(table, input, total_amount_id) {
  var filter, tr, td, i, totalViewable = 0;
  filter = input.value.toUpperCase();
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[1];
    tds = tr[i].getElementsByTagName("td")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
        totalViewable += parseFloat(tds.innerHTML);
        document.getElementById(total_amount_id).innerHTML = "$" + totalViewable.toFixed(2);
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

然后使用不同的参数调用该函数:

var table1 = document.getElementById("dateTable");
var input1 = document.getElementById("event_date_range");
var total_amount_id1 = "total_amount_td";
filterFunction(table1, input1, total_amount_id1);
var table2 = document.getElementById("dateTable2");
var input2 = document.getElementById("event_date_range2");
var total_amount_id2 = "total_amount_td2";
filterFunction(table2, input2, total_amount_id2);