我想调用一个函数,每当我将鼠标悬停在表中的一行上时,该函数都会打印该行的内容。到目前为止,我有这个:
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>
我徘徊在上面。
您可以通过调用textContent
获得单元格的文本。如果需要使用col/row索引,可以通过在行或表(body)内抓取元素的位置索引来获取。
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>
使用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>
使用onmouseenter
而不是onmouseover
阅读
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>