首页 > 解决方案 > 在表行悬停时调用函数

问题描述

我想调用一个函数,每次我将鼠标悬停在表格中时打印一行的内容。到目前为止,我有这个:

function tablemouseover(event) {
  console.log(event.target);
}
<table>
  <tr onmouseover='tablemouseover(event)'>
    <td>times[row]</td>
    <td>locations[row][0]</td>
    <td>locations[row][1]</td>
    <td>AllDistances[row]m</td>
  </tr>
</table>

然而,这只是让我<td>徘徊。

标签: javascripthtmljquerycssdom

解决方案


用于closest('tr')在 DOM 树中搜索最近的tr父级,然后innerHTML像这样记录它:

function tablemouseover(event){
   console.log(event.target.closest('tr').innerHTML);
}
<table>
<tr onmouseover='tablemouseover(event)'>
<td>times[row]</td>
<td>locations[row][0]</td>
<td>locations[row][1]</td>
<td>AllDistances[row]m</td>
</tr>
</table>


推荐阅读