我有一个 html 表,我正在尝试使用 jJavascript 在一行失去焦点时触发一个事件,但“模糊”事件似乎不正确,因为没有任何东西被触发:
(我在做什么的快速示例)
<tr class="tableRow">
<td class="tg-amwm" contentEditable="true">hours</td>
<td class="tg-amwm" contentEditable="true">minutes</td>
<td class="tg-amwm" contentEditable="true">hours</td>
<td class="tg-amwm" contentEditable="true">minutes</td>
</tr>
我正在使用以下内容:
var rows = document.getElementsByClassName("tableRow");
for(i = 0; i < rows.length; i++) {
rows[i].addEventListener("blur", function(){console.log("row left!");});
}
但控制台中没有出现任何内容 - 我是否误解了事件/DOM 结构?
最佳答案
行可能永远不会获得焦点,但其中的单元格会。
不幸的是,blur
不会冒泡。但是,如果您在每个单元格上勾选 blur
,然后单击其中一个单元格为其提供焦点,然后单击其他单元格以将焦点移开,它应该可以工作:
var cells = document.querySelectorAll(".tableRow td");
for (var i = 0; i < cells.length; i++) {
cells[i].addEventListener("blur", handler);
}
function handler() {
console.log("row left!");
}
<p>Click a cell below to give it focus</p>
<table>
<tbody>
<tr class="tableRow">
<td class="tg-amwm" contenteditable>hours</td>
<td class="tg-amwm" contenteditable>minutes</td>
<td class="tg-amwm" contenteditable>hours</td>
<td class="tg-amwm" contenteditable>minutes</td>
</tr>
</tbody>
</table>
<p>Click here to take focus away</p>
或者,使用 focusout
,它最初是一个仅限 IE 的事件,但已被添加到 Chrome,但据我所知,Firefox 还没有:
document.querySelector("table").addEventListener("focusout", function() {
console.log("Left!");
});
<p>Click a cell below to give it focus</p>
<table>
<tbody>
<tr class="tableRow">
<td class="tg-amwm" contenteditable>hours</td>
<td class="tg-amwm" contenteditable>minutes</td>
<td class="tg-amwm" contenteditable>hours</td>
<td class="tg-amwm" contenteditable>minutes</td>
</tr>
</tbody>
</table>
<p>Click here to take focus away</p>
给 jQuery 用户的旁注:jQuery 使 focus
和 blur
冒泡,即使它们不是原生的,所以你可以使用事件委托(delegate)对于上面的 jQuery。
关于当表格行失去焦点时运行代码的 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39427553/