在此示例中,我不理解此js代码。该代码用于突出显示单击时的单元格。与其为每个(可能很多)分配一个onclick处理程序,我们将在element上设置“ catch-all”处理程序。它将使用event.target获取被点击的元素并突出显示它。但是我在这里并没有弄清楚js部分。我想对此进行详细说明,以及是否有其他方法可以做同样的事情。
let table = document.getElementById('bagua-table');
let selectedTd;
table.onclick = function(event) {
let target = event.target;
while (target != this) {
if (target.tagName == 'TD') {
highlight(target);
return;
}
target = target.parentNode;
}
}
function highlight(node) {
if (selectedTd) {
selectedTd.classList.remove('highlight');
}
selectedTd = node;
selectedTd.classList.add('highlight');
}
#bagua-table td {
width: 150px;
text-align: center;
padding-top: 5px;
padding-bottom: 12px;
background-color:#000;
color: #fff;
}
#bagua-table .highlight {
background: red;
}
<table id="bagua-table">
<tr>
<td class="nw"><strong>Northwest</strong></td>
<td class="n"><strong>North</strong></td>
<td class="ne"><strong>Northeast</strong></td>
</tr>
<tr>
<td class="w"><strong>West</strong></td>
<td class="c"><strong>Center</strong></td>
<td class="e"><strong>East</strong></td>
</tr>
<tr>
<td class="sw"><strong>Southwest</strong></td>
<td class="s"><strong>South</strong></td>
<td class="se"><strong>Southeast</strong></td>
</tr>
</table>
答案 0 :(得分:1)
代码正在做的是在<table>
处理事件。当用户单击任意一个单元格时,将生成一个事件并冒泡直到父元素。在这种情况下,最初的target
是被单击的单元格,并且if (target.tagName == 'TD')
代码块被触发。依次调用highlight
函数,通过从上一个突出显示的单元格中删除.highlight
类并将其添加到当前目标单元格中来设置新的突出显示单元格。
为了更加健壮,代码不对生成事件的元素进行假设,因为<td>
单元格还可以包含其他html标签。这就是为什么它需要具有while (target != this)
循环的原因。原始目标可能不是<td>
标签,但它的祖先之一将是