为什么我不能在 td >p 元素上添加 "keydown" 事件?
Why I can't add "keydown" event on td >p element?
我想在用户按下 td 元素内 p 标签内的键时触发一些动作,这里是我 table.
上的“td”的 HTML
问题是,当我将 keydown
事件添加到每个段落元素时,我没有看到任何响应。这是我的做法。
document.querySelectorAll('tr').forEach((row) => {
if (row.rowIndex > 0) {
row.querySelectorAll('td').forEach((cell) => {
cell.contentEditable = true;
cell.querySelectorAll('p').forEach((prg) => {
prg.addEventListener('keydown', () => {
console.log('test');
});
});
});
}
});
<table>
<tr></tr>
<tr>
<td data-property="phone" contenteditable="true">
<p data-property="phone" class="sub-cell">34567890</p>
<p data-property="phone" class="sub-cell">5511525298ss</p>
<p data-property="phone" class="sub-cell">5511525298</p>
</td>
</tr>
</table>
我在“td”元素上有一些其他的“keydown”事件,但是当我删除它们时它仍然不起作用。
当我使用“点击”事件而不是“按下”事件时,我得到了我期望的响应。
我在这里读到 https://www.w3schools.com/Jsref/event_onkeydown.asp“p”和 table 元素支持按键事件。
我需要获取正在进行文本编辑的 p 以更新服务器信息,因此在 table 单元格上添加事件对我不起作用。
我非常感谢对此提供的任何帮助、阅读链接或建议。
如果您将 contentEditable 移动到段落标签上,它将起作用。
document.querySelectorAll('tr:not(:first-child) td p').forEach((prg) => {
prg.setAttribute('contentEditable', true);
prg.addEventListener('keydown', () => {
console.log('test');
});
});
<table>
<tr>
<td colspan='10'>First row</td>
</tr>
<tr>
<td data-property="phone">
<p data-property="phone" class="sub-cell">34567890</p>
<p data-property="phone" class="sub-cell">5511525298ss</p>
<p data-property="phone" class="sub-cell">5511525298</p>
</td>
</tr>
</table>
我想在用户按下 td 元素内 p 标签内的键时触发一些动作,这里是我 table.
上的“td”的 HTML问题是,当我将 keydown
事件添加到每个段落元素时,我没有看到任何响应。这是我的做法。
document.querySelectorAll('tr').forEach((row) => {
if (row.rowIndex > 0) {
row.querySelectorAll('td').forEach((cell) => {
cell.contentEditable = true;
cell.querySelectorAll('p').forEach((prg) => {
prg.addEventListener('keydown', () => {
console.log('test');
});
});
});
}
});
<table>
<tr></tr>
<tr>
<td data-property="phone" contenteditable="true">
<p data-property="phone" class="sub-cell">34567890</p>
<p data-property="phone" class="sub-cell">5511525298ss</p>
<p data-property="phone" class="sub-cell">5511525298</p>
</td>
</tr>
</table>
我在“td”元素上有一些其他的“keydown”事件,但是当我删除它们时它仍然不起作用。
当我使用“点击”事件而不是“按下”事件时,我得到了我期望的响应。
我在这里读到 https://www.w3schools.com/Jsref/event_onkeydown.asp“p”和 table 元素支持按键事件。
我需要获取正在进行文本编辑的 p 以更新服务器信息,因此在 table 单元格上添加事件对我不起作用。
我非常感谢对此提供的任何帮助、阅读链接或建议。
如果您将 contentEditable 移动到段落标签上,它将起作用。
document.querySelectorAll('tr:not(:first-child) td p').forEach((prg) => {
prg.setAttribute('contentEditable', true);
prg.addEventListener('keydown', () => {
console.log('test');
});
});
<table>
<tr>
<td colspan='10'>First row</td>
</tr>
<tr>
<td data-property="phone">
<p data-property="phone" class="sub-cell">34567890</p>
<p data-property="phone" class="sub-cell">5511525298ss</p>
<p data-property="phone" class="sub-cell">5511525298</p>
</td>
</tr>
</table>