尝试阅读我引用的 javascript 书来学习这门语言,但在循环访问特定行的 sibling 时卡住了。 W3schools 和 W3 没有我要找的东西。下面是一个功能演练...
内容如下:创建 countRecords() 函数。该函数的作用是统计数据表中表头后的可见行数。然后,总数显示在 ID 为“records”的表格单元格中。将以下命令添加到函数中:
一个。创建一个名为 headRow 的对象,它指向 ID 为“titleRow”的表行。创建一个名为 rowCount 的变量,将其初始值设置为 0。
创建一个使用家族引用的 for 循环,从 headRow 的第一个兄弟开始,然后移动到下一个兄弟,直到没有兄弟为止。在 for 循环中。测试是否是当前下一个兄弟节点的名称,直到没有兄弟节点为止。 for循环内测试当前节点的节点名是否等于“TR”。如果是,则测试其显示样式的值是否等于空文本字符串。如果是(表明它在文档中可见),则将 rowCount 变量的值增加 1。
将“记录”表单元格的文本更改为 rowCount 变量的值。不要使用 innerHTML。创建一个包含 rowCount 变量值的文本节点,并将其分配给名为 txt 的变量。创建一个名为 record 的变量来存储对元素“records”表单元格的引用。
插入一个 if 条件来测试“records”单元格是否有任何子节点。如果是这样,请将“记录”表格单元格的文本节点替换为创建的文本节点 (txt)。如果它没有将文本节点附加到单元格。
var headRow; // part a
var rowCount = 0;
//part b 这是我迷路的地方。我知道我需要访问 id titleRow 但不确定如何专门为此设置我的循环
headRow = document.getElementById("titleRow");
for(var i=0; i<headrow.length; i++)
{
if (something is not equal == "TH")
{
make code happen here
}
if (is "TR" == ""){
rowCount = +1;
}
//c部分
var txt = document.createTextNode(rowCount);
var record = document.getElementsById("records")
//d 部分暂缓这部分,直到我弄清楚 a、b、c。
HTML 支持片段:
<table id="filters">
<tr><th colspan="2">Filter Product List</th></tr>
<tr>
<td>Records: </td>
<td id="records"></td>
</tr>
<table id="prodTable">
<tr><th colspan="8">Digital Cameras</th></tr>
<tr id="titleRow">
<th>Model</th>
<th>Manufacturer</th>
<th>Resolution</th>
<th>Zoom</th>
<th>Media</th>
<th>Video</th>
<th>Microphone</th>
</tr>
感谢您的帮助!
最佳答案
您应该查看 nextSibling
属性(property)。我不确定你想要多严格地遵循你的书,但是 while
循环似乎比 for
更合适:
var headRow = document.getElementById("headRow");
var rowCount = 0;
var cRow = headRow; // used as a reference to the current row
while (cRow = cRow.nextSibling) // While there is a next sibling, loop
{
if (cRow.tagName == "TR" && cRow.style.display === "")
rowCount++; // increment rowCount by 1
}
如果您坚持使用 for
循环,我想您可以这样做:
var headRow = document.getElementById("headRow");
var rowCount = 0;
for (var cRow = headRow.nextSibling; cRow = cRow.nextSibling;)
{
if (cRow.tagName == "TR" && cRow.style.display === "")
rowCount++; // increment rowCount by 1
}
关于javascript - 循环遍历特定行的 sibling /设置功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2461312/