本文介绍了使用JS从html表的第一列搜索值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这张桌子
<th>Example No.</th>
<th>Column 1</th>
<tr>
<td id="SampleId">3512376894</td>
<td>two.test2@hotmail.com</td>
</tr>
我有按所有列搜索值的脚本.但我想要做的就是仅使用 td id 按第一列搜索值.但我不知道该怎么做.请帮助我做到这一点?谢谢!
I have script that search the values by all columns. But all I want to do is search the values by first column only with td id. But I don't know how to do that. Please kindly, help me to do that? Thanks!
这是 JScript:
Here's the JScript:
function doSearch() {
var searchText = document.getElementById('searchTerm').value;
var targetTable = document.getElementById('dataTable');
var targetTableColCount;
for (var rowIndex = 0; rowIndex < targetTable.rows.length; rowIndex++) {
var rowData = '';
if (rowIndex == 0) {
targetTableColCount = targetTable.rows.item(rowIndex).cells.length;
continue; //do not execute further code for header row.
}
for (var colIndex = 0; colIndex < targetTableColCount; colIndex++) {
rowData += targetTable.rows.item(rowIndex).cells.item(colIndex).textContent;
if (rowIndex <= 1) {
document.getElementById('noresults').style.display = "block";
}
}
}
}
推荐答案
使用下面的代码片段在给定的列中搜索特定术语.
Use the snippet below to search within a given column for a certain term.
<!-- HTML -->
<table id="dataTable">
<th>Example No.</th>
<th>Column 1</th>
<th>Column 2</th>
<tr>
<td>345678917</td>
<td>Test 1</td>
<td>one_test1@gmail.com</td>
</tr>
<tr>
<td>3512376894</td>
<td>Test 2</td>
<td>two.test2@hotmail.com</td>
</tr>
</table>
// JavaScript
window.onload = function(){
var term = "3512376894"; // term you're searching for
var column = 0; // which column to search
var pattern = new RegExp(term, 'g'); // make search more flexible
var table = document.getElementById('dataTable');
var tr = table.getElementsByTagName('TR');
for(var i = 0; i < tr.length; i++){
var td = tr[i].getElementsByTagName('TD');
for(var j = 0; j < td.length; j++){
if(j == column && td[j].innerHTML == term){
// for more flexibility use match() function and the pattern built above
// if(j == column && td[j].innerHTML.match(pattern)){
console.log('Found it: ' + td[j].innerHTML);
}
}
}
};
输出:
Found it: 3512376894
工作 jsBin 或 jsFiddle 或这个版本 jsFiddle
这篇关于使用JS从html表的第一列搜索值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!