javascript - contenteditable 元素的子元素的事件

标签 javascript jquery

我有

myDiv.bind('keypress', '> *', function(event) { console.log('keypress') });

但是好像不行。

myDiv 是 contenteditable,我正在尝试访问正在编辑的 p 元素。

http://jsfiddle.net/nb5UA/5/ (尝试在点击回车后创建的 div 中输入)

最佳答案

This is barely possible with contenteditable seeing as the elements do not hold input like events and therefore do not have real focus, so you can't actually determine the event.target. The event.target will always be the container that has the attribute contenteditable="true".

However you can use the DOMCharacterDataModified event like the example & demo below.

$('#test').on('DOMCharacterDataModified',  function( event ) {
    if($(event.target).parent().attr('id') === 'test') { // Reference 1 
        alert('modified');
    }
});

演示:http://jsfiddle.net/nb5UA/15/

Reference 1: The if statement is checking that the event.target is a direct child of the #test container.

浏览器对 DOMCharacterDataModified 的支持还不错。 不支持,我找不到太多关于该事件的信息,所以如果有人有好的资源,请在评论中分享。

关于javascript - contenteditable 元素的子元素的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18169626/

相关文章:

javascript - 使用JS拖放时防止掉落在子元素内

javascript - jquery访问所有具有id属性的元素

javascript - 根据其他属性(语言)更改 JavaScript 属性

javascript - 如何使用 JavaScript 进行验证

javascript - 如何将远程 javascript 加载到 SpiderMonkey 上下文中?

javascript - 数据绑定(bind)不在 View 页面中显示数据

javascript - 使用 jQuery 更改对象宽度和窗口大小

jquery - 允许用户编辑 CSS

php - Web 应用程序性能改进

javascript - JQuery - 在 'for' 语句中循环 .load()