gpt4 book ai didi

javascript - 使用事件委托(delegate)突出显示表中的单元格

转载 作者:行者123 更新时间:2023-12-02 23:27:23 26 4
gpt4 key购买 nike

我不明白这个例子中的js代码。此代码用于在单击时突出显示单元格。我们将在元素上设置“catch-all”处理程序,而不是为每个(可以有很多)分配一个 onclick 处理程序。它将使用 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>

最佳答案

代码正在做的是处理 <table> 处的事件。当用户单击任一单元格时,就会生成一个事件并向上冒泡到父元素。初始target在本例中是被单击的单元格,if (target.tagName == 'TD')代码块被触发。这又调用highlight函数通过删除.highlight来设置新的突出显示单元格最后突出显示的单元格中的类并将其添加到当前目标单元格中​​。

为了更加健壮,代码不会假设哪个元素生成事件,因为 <td>单元格还可以包含其他 html 标签。这就是为什么它需要有 while (target != this)环形。原始目标可能不是 <td>标签,但它的祖先之一将是。

关于javascript - 使用事件委托(delegate)突出显示表中的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56677769/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com