Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

javascript - Keypress event on nested content editable (jQuery)

I have a CONTENTEDITABLE div and inside that div I have a CONTENTEDITABLE span, what I want to do is being able to handle the onkeypress event on the inner SPAN.

So, the javascript code would be:

$(function()
{
    $('#someid').keypress(function(event){alert('test');});
});

And the HTML content would be:

<div id="mydiv" contenteditable="true">
editable follows:<span id="someid" contenteditable="true">Some TEXT</span>
</div>

If you test it on a browser you'll see you won't see the 'test' dialog when you press a key over Some TEXT, I know the problem is that the event is being triggered in the parent div, so the SPAN doesn't get the event, also because it doesn't have the focus. So I'd like your help to find a solution for this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The exact code you posted in your question seems to work just fine at http://jsfiddle.net/gaby/TwgkC/3/

Tested and working with FF, Opera, Chrome, Safari, IE8 ..

only change is the removal of the comment which in its current form creates a syntax error.

The #someid need to have focus in order for the keypress to work.
If you want your code to give focus to the element right after creating it, use the .focus() method.

function AppendSpan()
{
    $('#mydiv').append('<span id="someid" contenteditable="true">Some TExt</span>');
    //Then I want to handle the keypress event on the inserted span
    $('#someid').keypress(function(event){
          //do something here
          alert(this.id);
    }).focus();// bring focus to the element once you append it..
}

Update

Two ways to handle this (the fact that there are nested contenteditable elements), not sure if any is acceptable for your case but here they are..

  1. wrap the new contenteditable span in another one, which is set to have contenteditable="false"
    (demo: http://jsfiddle.net/gaby/TwgkC/10/)
  2. make #mydiv to not be contenteditable once you add the span..
    (demo: http://jsfiddle.net/gaby/TwgkC/11/)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...