向表搜索功能

问题描述 投票:0回答:1

我已经使用了以下代码,将我的数组转换为HTML表。

const MOUNTAINS = [
{name: "Kilimanjaro", height: 5895, place: "Tanzania"},
{name: "Everest", height: 8848, place: "Nepal"},
{name: "Mount Fuji", height: 3776, place: "Japan"},
{name: "Vaalserberg", height: 323, place: "Netherlands"},
{name: "Denali", height: 6168, place: "United States"},
{name: "Popocatepetl", height: 5465, place: "Mexico"},
{name: "Mont Blanc", height: 4808, place: "Italy/France"}
];


function buildTable(data) {
let table = document.createElement("table");

let fields = Object.keys(data[0]);
let headRow = document.createElement("tr");
fields.forEach(function(field) {
  let headCell = document.createElement("th");
  headCell.appendChild(document.createTextNode(field));
  headRow.appendChild(headCell);
});
table.appendChild(headRow);

data.forEach(function(object) {
  let row = document.createElement("tr");
  fields.forEach(function(field) {
    let cell = document.createElement("td");
    cell.appendChild(document.createTextNode(object[field]));
    if (typeof object[field] == "number") {
      cell.style.textAlign = "right";
    }
    row.appendChild(cell);
  });
  table.appendChild(row);
});
return table;
}
document.querySelector("#mountains").appendChild(buildTable(MOUNTAINS));

我现在正在尝试对该表进行过滤/搜索。用户输入“ K”时,仅应显示以字母K开头的山脉。我尝试了以下方法:

function searchTable() {
var input, filter, table, tr, td, i;
input = document.getElementById(myInput);
filter = input.value.toUpperCase();
table = document.getElementsByTagName("table");
tr = tr.getElementsByTagName("tr");
for(i = 0; < tr.length; i++;){
    td = tr[i].getElementsByTagName("td")[0];
    if(td.innerHTML.toUpperCase().indexOf(filter)>-1){
        tr[i].style.display=""
    }else{
        tr[i.style.display="none";]

    }

}
}

当我链接列表并在HTML文档中使用输入标签时,它不起作用。我对javascript还是很陌生,希望大家能帮助我解决问题或做不同的事情。

谢谢!

javascript arrays search html-table
1个回答
0
投票

尝试以下jquery。 txtSearch是输入文本字段的ID

$("#txtSearch").on("keyup", function () {
            $("#mountains .divnodata").remove();
            var value = $(this).val().toLowerCase();

            $("#mountains tr td:nth-of-type(1)").filter(function () {
                $(this).parent().toggle($(this).text().toLowerCase().indexOf(value) ==0);// >-1
            });

            if ($("#mountains tr:not(:first):visible").length == 0) {
                $("#mountains").append("<div class='divnodata'><div class='col'>No data</div></div>");
            }
        });
© www.soinside.com 2019 - 2024. All rights reserved.