使用javascript在HTML中搜索2列而不是1列 [英] Search 2 columns instead of 1 in HTML using javascript

查看:81
本文介绍了使用javascript在HTML中搜索2列而不是1列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用javascript使html表可搜索但我无法使其工作(它只能使用1列),我在搜索之前搜索但所有结果都不同,我想编辑我有代码。任何人都可以帮忙,告诉我我需要编辑什么才能使用2列[1]& [2]?谢谢。



我尝试过:



这是我的html搜索和表格:

I'm trying to make the html table searchable using javascript but i can't get it to work(It is only working with only 1 column), I searched before asking but all results are different and i want to edit the code i have instead.Can anyone help please and tell me what I need to edit for it to work with 2 columns [1] & [2]?and Thanks.

What I have tried:

This is my html search and table:

<input type="search" id="myInput" onkeyup="searchTable()" class="form-control">
<table id="myTable" class="table table-striped table-responsive">





这是我正在使用的脚本:



This is the script i'm using:

function searchTable() {
  // Declare variables 
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[1];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    } 
  }
}

推荐答案

试试这个:
for (i = 0; i < tr.length; i++) {

    td = tr[i].getElementsByTagName("td");

	if(td.length > 0){ // to avoid th

       if (td[0].innerHTML.toUpperCase().indexOf(filter) > -1 || td[1].innerHTML.toUpperCase().indexOf(filter) > -1) {
         tr[i].style.display = "";
       } else {
         tr[i].style.display = "none";
       }

    }
 }


这篇关于使用javascript在HTML中搜索2列而不是1列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆