[英]Attaching keypress and focusout event to elements inside contenteditable div
I want to attach keypress
and focusout
event handlers to a paragraph inside contenteditable div
. 我要附加
keypress
和focusout
事件处理程序CONTENTEDITABLE内一个段落div
。
The following code doesn't seem to work: 以下代码似乎无效:
<div contenteditable="true">
<p id="p1">Test</p>
<p id="p2">Test</p>
<p id="p3">Test</p>
</div>
$('#p1').bind('keypress', function(e) {
alert('keypress');
});
$('#p1').focusout(function(e) {
alert('focusout');
});
Basically the contenteditable
is the one that will respond to events dispatched from the inner Nodes. 基本上,
contenteditable
可编辑的内容将响应内部节点发出的事件。 If we get the caret position and than target it's range's parentNode - than we can retrieve the desired ID 如果我们获得插入符号的位置,然后将其定位为范围的parentNode,则可以获取所需的ID
$('[contenteditable]').on('keypress focusout', function(ev) { var node = window.getSelection().getRangeAt(0).commonAncestorContainer; var nodeParent = node.parentNode; // Do something if parent node ID is "p1" if( nodeParent.id === "p1") { console.log( nodeParent.id +' '+ ev.type ); // or whatever you need to do here } });
<div contenteditable="true"> <p id="p1">TestP1 do someting on keypress</p> <p id="p2">TestP2 is Not Interesting</p> </div> <script src="//code.jquery.com/jquery-3.1.0.js"></script>
There's an answer over here: https://stackoverflow.com/a/18772205/2100255 这里有一个答案: https : //stackoverflow.com/a/18772205/2100255
Basically, you need to wrap your inner contenteditables with non-contenteditables. 基本上,您需要使用非contenteditables包装内部的contenteditables。 The event fires off the node which declares contenteditable=true.
该事件触发声明contenteditable = true的节点。
You can do it as below Instead of click event you can change it to event on which you want to track the change.I am using click for example 您可以按以下方式进行操作,而不是单击事件,您可以将其更改为要跟踪更改的事件。
$("div").click(function(e){ console.log($("#"+$(e.target)[0].id).text()); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.