以下代码搜索网页上任何表格的第一列,我想搜索第二列的数据。我需要做什么编辑才能获得所需的输出?
<script>
function myFunction() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
答案 0 :(得分:0)
<script>
function myFunction() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
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";
}
}
}
}
</script>
只需使用td数组的索引'1'即可得到第二列。
答案 1 :(得分:0)
第一列为td 0,第二列为td 1
只需更改此行:
td = tr [i] .getElementsByTagName(“td”)[0];
到
td = tr [i] .getElementsByTagName(“td”)[1];
function myFunction() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
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";
}
}
}
}
<input id="myInput" type="text" onkeyup="myFunction()"/>
<table id="myTable" border="1">
<tr><td>1</td><td>John</td></tr>
<tr><td>2</td><td>Jonny</td></tr>
<tr><td>3</td><td>Ram</td></tr>
<tr><td>4</td><td>Shyam</td></tr>
</table>