【发布时间】:2019-06-04 11:33:12
【问题描述】:
当我取消选中该复选框时,我希望表格行消失。它必须仅基于 JavaScript(学校练习)。
复选框的创建工作,但我无法将显示设置为“无”
还有更多的 TR,但我已经删除了其中的大部分,因为它对解决下面的代码没有任何附加价值。
// Get parent of checkbox
var searchTr = document.querySelectorAll("#searchTable tr");
// add checkbox to parent
for (i = 1; i < searchTr.length; i++) {
var chkbox = document.createElement("input");
chkbox.type = "checkbox";
chkbox.setAttribute("class", "chkbox");
searchTr[i].appendChild(chkbox);
chkbox.checked = true;
chkbox.addEventListener("change", hideMe);
function hideMe() {
searchTr[i].style.display = "none";
}
}
<table id="searchTable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th class="th-sm">Name
</th>
<th class="th-sm">Position
</th>
<th class="th-sm">Office
</th>
<th class="th-sm">Age
</th>
<th class="th-sm">Start date
</th>
<th class="th-sm">Salary
</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
</tbody>
</table>
【问题讨论】:
-
我假设这个练习不允许你使用 jquery?
-
确实是Javascript。
-
我认为在声明和调用函数时都需要在函数中传递“i”
-
要在函数中使用变量,您需要将其从回调传递到声明(添加参数作为下面的答案),然后函数将能够在内部使用它它。
-
你的意思是输入 function hideMe(i){ searchTr[i].style.display = "none"; }?我在 chrome 的开发者工具中的控制台给出了以下消息: Uncaught TypeError: Cannot read property 'style' of undefined at HTMLInputElement.hideMe
标签: javascript html for-loop