javascript 检测其父为 contenteditable div 的 contenteditable 子项的 keyup 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18771651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect keyup event of contenteditable child whose parent is a contenteditable div
提问by Joshua Robinson
Goal:Attach a keydown event handler to a contenteditable span that is the child of a contenteditable div.
目标:将 keydown 事件处理程序附加到作为 contenteditable div 的子级的 contenteditable span。
Problem:If you type in the span the parent event is triggered not the childs. What I want is the child to trigger so I can grab the text. I only want THAT contenteditable child as there will be many.
问题:如果您输入跨度,将触发父事件而不是子事件。我想要的是孩子触发所以我可以抓住文本。我只想要那个可满足的孩子,因为会有很多。
HTML/JS is below and the fiddle link is here: http://jsfiddle.net/aBYpt/4/
HTML/JS 在下面,小提琴链接在这里:http: //jsfiddle.net/aBYpt/4/
HTML
HTML
<div class="parent" contenteditable="true">
Parent div text.
<span class="child" contenteditable="true">First child span text.</span>
<span class="child" contenteditable="true">Second child span text.</span>
<span class="child" contenteditable="true">Third child span text.</span>
</div>
<div id="console"></div>
JavaScript/jQuery
JavaScript/jQuery
$(document).on( 'keyup', '.parent', function() {
$('#console').html( 'Parent keyup event fired.' );
//do stuff
});
$(document).on( 'keyup', '.child', function() {
$('#console').html( 'Child keyup event fired.' );
//do stuff
});
**Note: Event handling is delegated to document because elements are dynamically added.
**注意:事件处理委托给文档,因为元素是动态添加的。
采纳答案by Joshua Robinson
So this is a bug. Workaround confirmed for FF23 and CHROME29 (on linux with no vm so can't test IE). You mustset the wrapping spans as contenteditable false, you can't just omit declaring the contenteditable attribute, which is rediculous. Solution via Keypress event on nested content editable (jQuery)
所以这是一个错误。针对 FF23 和 CHROME29 确认的解决方法(在没有虚拟机的 linux 上,因此无法测试 IE)。您必须将包装跨度设置为 contenteditable false,您不能只是省略声明 contenteditable 属性,这是可笑的。通过可编辑嵌套内容 (jQuery) 上的 Keypress 事件解决方案
Here is the fiddle: http://jsfiddle.net/aBYpt/14/
这是小提琴:http: //jsfiddle.net/aBYpt/14/
HTML
HTML
<div class="parent" contenteditable="true">
Parent div text.
<span contenteditable="false">
<span class="child" contenteditable="true">First child span text.</span>
<span contenteditable="false">
<span class="child" contenteditable="true">Second child span text.</span>
</span>
</div>
<div id="console"></div>
JavaScript/jQuery
JavaScript/jQuery
$(document).on( 'keyup', '.parent', function() {
//do stuff
$('#console').html( 'Parent keyup event fired.' );
});
$(document).on( 'keyup', '.child', function(e) {
//do stuff
$('#console').html( 'Child keyup event fired.' );
e.stopPropagation();
});