SearchingThrough使用输入标签的表

时间:2018-01-09 21:28:32

标签: javascript html css search

我正在尝试搜索一个没有输入标签的工作表,但我希望将输入标记保存在表格单元格中。我尝试使用td.firstElementChild.value,但这不起作用....为了搜索表格,我需要修复什么?

这是我的小提琴:https://jsfiddle.net/Souleste/1fxxzoe7/114/

1 个答案:

答案 0 :(得分:0)

一种解决方案是在所有输入元素中包含一个公共className。

您在创建输入控件时已经这样做了:

input1.className = 'input';

尽管如此,我建议使用更具描述性的className,但只要className对页面上的输入控件是唯一的,它们都可以工作:

input1.className = 'search-input';

您还拥有每个TR(行)元素的唯一ID。

tr.id = 'row' + rowCount;

在输入元素上添加此id作为数据属性,如下所示:

input1.setAttribute('data-tr-id', 'row' + rowCount);

现在,通过className获取输入并检查值:

var inputElements = document.getElementsByClassName('search-input');
inputElements.foreach(function(item, index){
     var value = item.value;
     // use the data-tr-id attribute to find the TR element to hide/show
     var trElementId = item.getAttribute('data-tr-id');
     var trElement = document.getElementById(trElementId);
     // do the value comparison and hide/show as needed
     if (value.toUpperCase().indexOf(filter) > -1) {
         tr.style.display = '';
     } else {
         tr.style.display = 'none';
     }
});