当表格行失去焦点时运行代码的 JavaScript

标签 javascript dom-events onblur

我有一个 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 使 focusblur 冒泡,即使它们不是原生的,所以你可以使用事件委托(delegate)对于上面的 jQuery。

关于当表格行失去焦点时运行代码的 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39427553/

相关文章:

javascript - 为什么 iOS Safari 会两次触发窗口焦点事件?

javascript - 当文本区域/输入模糊/失去焦点时仍然显示 div

python - javascript 中的 OnChange 或 OnBlur 事件在 Django 中运行 python 函数并返回结果?

javascript - 在第一次绘制之前修改 body 的类

javascript - 使用 sinon 模拟日期对象

javascript - 用于预选下拉值的 YUI 自定义事件?

javascript - onBlur 警报在 Safari 中持续触发

javascript - 当对象在视口(viewport)中可见时执行操作

javascript - 聚焦 SWF 对象时停止滚动网页

javascript - 从 html 表单调用 Javascript