[英]Attaching keypress and focusout event to elements inside contenteditable div
我要附加keypress
和focusout
事件處理程序CONTENTEDITABLE內一個段落div
。
以下代碼似乎無效:
<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');
});
基本上, contenteditable
可編輯的內容將響應內部節點發出的事件。 如果我們獲得插入符號的位置,然后將其定位為范圍的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>
這里有一個答案: https : //stackoverflow.com/a/18772205/2100255
基本上,您需要使用非contenteditables包裝內部的contenteditables。 該事件觸發聲明contenteditable = true的節點。
我已更改解決方案,請參閱最新的小提琴
$(document).on('keypress', '#p1[contenteditable="true"]', function(e) {
alert("test");
});
您可以按以下方式進行操作,而不是單擊事件,您可以將其更改為要跟蹤更改的事件。
$("div").click(function(e){ console.log($("#"+$(e.target)[0].id).text()); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.