[英]Why I can't add "keydown" event on td >p element?
I want to trigger some action when user press a key inside ap tag inside a td element, here is the HTML of a "td" on my table.当用户按下 td 元素内的 ap 标签内的键时,我想触发一些动作,这是我桌子上“td”的 HTML。
The problem is that when I add the keydown
event to every paragraph element I don't see any response.问题是当我将keydown
事件添加到每个段落元素时,我看不到任何响应。 Here is how I did it.这是我的做法。
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>
I had some other "keydown" events on the "td" elements but when I removed them it still not working.我在“td”元素上有一些其他“keydown”事件,但是当我删除它们时它仍然无法正常工作。
When I use the "click" event instead "keydown" I obtain the response that I expect.当我使用“click”事件而不是“keydown”时,我得到了我期望的响应。
I read here https://www.w3schools.com/Jsref/event_onkeydown.asp that keydown event is supported in "p" and table elements.我在这里读到 https://www.w3schools.com/Jsref/event_onkeydown.asp在“p”和表格元素中支持 keydown 事件。
I need to obtain the p in which the text editing is happening for update server info so add the event on the table cell is not working for me.我需要获取正在进行文本编辑的 p 以更新服务器信息,因此在表格单元格上添加事件对我不起作用。
I really appreciate any help with this, links to read or suggestions.我非常感谢任何帮助,阅读链接或建议。
If you shift the contentEditable onto the paragraph tags it will work.如果您将 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.