【问题标题】:Call Function on Tabel Row Hover在表格行悬停时调用函数
【发布时间】:2021-05-24 18:06:43
【问题描述】:

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

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>

但这只是让我&lt;td&gt; 我被悬停在上面。

【问题讨论】:

标签: javascript html jquery css dom


【解决方案1】:

您可以通过调用textContent 来获取单元格的文本。如果您想要 col/row 索引,您可以通过抓取元素在其行或表(正文)中的位置索引来获取它们。

const getChildIndex = node => 
  Array.prototype.indexOf.call(node.parentNode.children, node);

function tablemouseover(event) {
  const
    row = event.currentTarget,
    col = event.target,
    rowIndex = getChildIndex(row),
    colIndex = getChildIndex(col),
    allText = [...row.children].map(td => td.textContent);
  
  console.log(`Cell (${colIndex}, ${rowIndex}): ${event.target.textContent}`);
  console.log(`Row [${rowIndex}]: ${JSON.stringify(allText)}`);
}
table, th, td { border: thin solid grey; }
table { border-collapse: collapse; }
th, td { padding: 0.5em; }

.as-console-wrapper { max-height: 5.25em !important; }
<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>
    <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>

【讨论】:

    【解决方案2】:

    使用 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>

    【讨论】:

      【解决方案3】:

      使用onmouseenter 而不是onmouseover

      Read what different between

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

      【讨论】:

        猜你喜欢
        • 2013-01-04
        • 2011-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多