我在浏览网页时遇到问题 - 我需要在表格中找到一些已知的 innerHtml
,并影响包含 innerHtml 的标签的父标签。恐怕我几乎没有 JavaScript 游戏......
HTML 如下所示:
<table> <tbody>
<tr class="header">
<td>
<table> <tbody>
<tr class="header">
<td> <u> January </u> </td>
<td>foo</td>
</tr>
</tbody> </table>
</td>
</tr>
<tr class="header">
<td>
<table> <tbody>
<tr class="header">
<td> <u> February </u> </td>
<td>bar</td>
</tr>
</tbody> </table>
</td>
</tr>
</tbody> </table>
我正在尝试查找“January”并为父级添加背景颜色,这是我目前的代码:
var thetr = document.getElementsByTagName('tr');
for (j = 0; j < thetr.length; j++) {
var theTd1 = thetr[j].getElementsByTagName('td');
for (k = 0; k < theTd1.length; k++) {
var theTd2 = theTd1[l].getElementsByTagName('td');
for (m = 0; m < theTd2.length; k++) {
if (theTd2[j].innerHtml == "January") {
thetr[j].style.backgroundColor = "rgb(255, 195, 195)";
}
}
}
}
没有得到任何东西...如果我添加一个警报来向我显示它正在读取每个级别的 innerHtml
,我只会得到“未定义”。我的方法有多错误?提前谢谢你。
最佳答案
几件事:
- 始终检查浏览器控制台是否有错误。在那里你会看到类似的东西:
l
is not defined - 使用
querySelectorAll()
(或使用 jQuery)查找节点。你会避免很多悲伤。 - 除非创建全新的节点,否则在 Tampermonkey 脚本中使用
innerHtml
几乎总是错误的,而且即使它能工作一段时间也很脆弱。您的脚本或页面会随着最细微的变化而中断。 - 如果页面是 AJAX 驱动的,不管怎样,这样的静态方法都会失败。
对于静态页面,此演示显示了该行突出显示的 Vanilla.js:
var headerCells = document.querySelectorAll ("tr.header > td > u");
headerCells.forEach (uNode => {
if (/January/i.test (uNode.textContent) ) {
uNode.parentNode.parentNode.style.backgroundColor = "lime";
}
} );
<table> <tbody>
<tr class="header">
<td>
<table> <tbody>
<tr class="header">
<td> <u>January</u> </td>
<td>foo</td>
</tr>
</tbody> </table>
</td>
</tr>
<tr class="header">
<td>
<table> <tbody>
<tr class="header">
<td> <u>February</u> </td>
<td>bar</td>
</tr>
</tbody> </table>
</td>
</tr>
</tbody> </table>
或者,在 jQuery 中代码很简单:
$("tr.header > td > u:contains(January)").closest ("tr").css ("background", "lime");
对于静态页面或AJAX 驱动的页面,这里是一个完整的 Tampermonkey 脚本,可以正常工作:
// ==UserScript==
// @name _Highlight January
// @match *://YOUR_SERVER.COM/YOUR_PATH/*
// @require https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
//- The @grant directives are needed to restore the proper sandbox.
/* global $, waitForKeyElements */
waitForKeyElements ("tr.header > td > u:contains(January)", justLimen);
function justLimen (jNode) {
jNode.closest ("tr").css ("background", "lime");
}
关于javascript - 如何读取嵌套的 innerHtml 并将背景添加到父级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55366206/