表每行上的HTML事件侦听器



问题如下:

  • 我有一个表,其中的行具有按键侦听器
  • 每一行都有内容可编辑
  • 我想使包装tbody元素内容可编辑(以允许通过单击和拖动选择多行(
  • 如果我确实使tbody内容可编辑,则按键事件不再在行中触发
    • 只有tbody元素接收事件

主要问题是将tbody设置为可编辑会模糊表行的按键事件

编辑:指针事件有任何形式吗:键盘事件没有?

如何使行仍然接收事件,或者如何在不使tbody/table内容可编辑的情况下启用拖动和选择?

非常感谢任何反馈或帮助,谢谢!


如果描述不清楚,下面是一个示例代码片段:

<style>
table{
background-color: cyan;
}
table, th,td, tr{
border: 1px solid black;
border-collapse: collapse;
}

tr,td, th {
padding: 3px;
text-align: left;
height: 2em;
}

</style>
<div>
<table>
<thead style = "background-color:white">
<tr>
<th>Value</th>
</tr>
</thead>
<tbody> <!-- need to make this tbody contenteditable -->
<tr contenteditable = 'true' onkeypress='keyPressed(event)'>
<td>v1</td>
</tr>
<tr contenteditable = 'true' onkeypress='keyPressed(event)'>
<td>v2</td>
</tr>
</tbody>
</table>
</div>
<script>
function keyPressed(){
if(event.keyCode == 13){
event.preventDefault();
row = event.target;
row.insertAdjacentHTML('afterend',"<tr contenteditable = 'true' onkeypress='keyPressed(event)'><td></td></tr>");
row.nextSibling.focus();
}
}
</script>

document.querySelectorAll('contenteditable td')
.forEach(e => e.addEventListener("click", function() {
// Here, `this` refers to the element the event was hooked on
console.log("clicked")
}));

更清楚。

您可以使用element.target来查看实际被点击的元素。例如,在我的代码段中,tbodytrcontenteditable,但正如您在控制台中看到的,element.targetelement.currentTarget都检索了一个不同的字段,因此您知道可以这样使用它。

但我可能只是建议使用div,因为它们更容易使用。

document.querySelector('[contenteditable]').addEventListener("click", function(el) {
console.log(el.target,el.currentTarget)
});
/*
function keyPressed() {
if (event.keyCode == 13) {
event.preventDefault();
row = event.target;
row.insertAdjacentHTML('afterend', "<tr contenteditable = 'true' onkeypress='keyPressed(event)'><td></td></tr>");
row.nextSibling.focus();
}
}*/
table {
background-color: cyan;
}
table,
th,
td,
tr {
border: 1px solid black;
border-collapse: collapse;
}
tr,
td,
th {
padding: 3px;
text-align: left;
height: 2em;
}
<div>
<table>
<thead style="background-color:white">
<tr>
<th>Value</th>
</tr>
</thead>
<tbody contenteditable='true'>
<!-- need to make this tbody contenteditable -->
<tr contenteditable='true'>
<td>v1</td>
</tr>
<tr contenteditable='true'>
<td>v2</td>
</tr>
</tbody>
</table>
</div>

最新更新