Keypress event on nested content editable (jQuery)

后端 未结 2 1084
野的像风
野的像风 2020-12-10 07:45

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,

相关标签:
2条回答
  • You might be better to bind the keypress event to the #mydiv element like this:

    $('#mydiv').delegate("span", "keypress", function(){
        console.alert('A key has been pressed: ' + this.id);
    });
    

    On further investigation though, it seems that DOM elements such as regular spans and divs are incapable of receiving focus. You may be able to get around this however, by adding a tabindex attribute to each span.

    0 讨论(0)
  • 2020-12-10 08:48

    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/)
    0 讨论(0)
提交回复
热议问题