【发布时间】:2021-07-23 11:08:21
【问题描述】:
期望结果: 将 .csv 文件中的数据输入 PHP。从 .csv 文件中获取数据并存储到数组中。使用 PHP 将数组存储到 HTML 表中。使用搜索引擎使用 JavaScript 过滤行。
我在 JavaScript 中收到以下错误: 未捕获的类型错误:无法读取 null 的属性“textContent”
<script>
const searchInput = document.getElementById("search");
const rows = document.querySelectorAll("tbody tr");
//console.log(rows);
searchInput.addEventListener("keyup", function (event) {
//console.log(event);
const q = event.target.value.toLowerCase();
rows.forEach(row => {
//console.log(row);
row.querySelector("td").textContent.toLowerCase().startsWith(q);
? (row.style.display = "table-row")
: (row.style.display = "none");
} );
});
</script>
使用console.log,我已经能够确定它正在正确读取并循环遍历表中的每一行,但它无法循环遍历“td”来确定它是否与搜索引擎中的文本匹配。
如果该信息有用,则在整理行时,该数组是一个 NodeList。
如果需要,很乐意上传更多信息。提前感谢您的帮助!
编辑 添加最小的 HTML。该表包含 15 行,但出于此目的,仅添加了几行。此表是使用 PHP 从数组创建的。
EDIT 2标题添加到广告中
<html>
<head>
</head>
<body>
<input type="text" name="search" id="search" placeholder="Search for services..">
<table>
<thead>
<tr>
<th>Item #</th>
<th>Name</th>
<th>Type</th>
<th>Make</th>
<th>Model</th>
<th>Brand</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td><td>Cut & Blow Dry</td>
<td>Service</td>
<td></td>
<td></td>
<td>Hair by Cass</td>
<td>Haircut and style after</td>
</tr>
</tbody>
</table>
</body>
</html>
【问题讨论】:
-
row.querySelector("td")只会让您获得一行的第一个 TD 元素。您能否提供带有搜索框的最小 HTML 示例表? -
您的 HTML 不是那么有效。
<th>应该进入<thead>而不是<tbody> -
您的第一行不包含任何
td这就是您收到该错误的原因 -
我现在也在测试你的代码。我刚刚调整了我的 PHP 循环以在 中包含
。
标签: javascript php html