gpt4 book ai didi

javascript - 如何过滤图像表

转载 作者:行者123 更新时间:2023-11-30 10:58:46 25 4
gpt4 key购买 nike

我正在尝试使用搜索栏过滤图像表。当表格中有文本时我可以这样做,但我只希望表格中有图像。有没有办法以字符串的形式获取id或alt?

function search() {
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("champions");
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")[0].getAttribute("alt");
console.log(td);
if (td) {
//alert(td);
txtValue = td;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}

search();
Input: <input type="text" id="myInput" />
<br/>
<table id="champions">
<tr>
<td><img id="1" onclick="clicked()" draggable="true" ondragstart="drag(event)" src=".png" alt="1a"></td>
</tr>

</table>

正在调用搜索,但是当它到达 if(td) 时返回 null

最佳答案

您的代码存在的问题是,您要查找的 alt 属性是 img 标记的一个属性,但您的代码是在 td 标签。

你可以通过改变

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

td = tr[i].getElementsByTagName("td")[0].getElementsByTagName("img")[0].getAttribute("alt");

演示:

function search() {
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("champions");
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")[0].getElementsByTagName("img")[0].getAttribute("alt");
console.log(td);
if (td) {
//alert(td);
txtValue = td;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}

search();
Input: <input type="text" id="myInput" />
<br/>
<table id="champions">
<tr>
<td><img id="1" onclick="clicked()" draggable="true" ondragstart="drag(event)" src=".png" alt="1a"></td>
</tr>

</table>

关于javascript - 如何过滤图像表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58879791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com