I encountered a problem in my work these days. I googled and found the solution, but it was in English. I simply translated it so that more people can understand it
The translation is as follows:
I have an editable div and an editable span inside the DIV. I want the span to respond to keyboard events.
Here is the test JS code:
$(function()
{
$('#someid'). keypress(function(event){alert('test');});
});
Here is the test html code :
editable follows:Some TEXT
If you test in the browser, you You will see that when you press key on Some TEXT, no 'test' pop-up box pops up. I know that the reason for this problem is because the event is sent from the span's parent node div, so the span does not trigger the event. Of course It's also caused by span not having focus, so I want someone to help me find a solution.
Finally, some kind people helped solve this problem
I have submitted the solution code to your problem to http://jsfiddle.net/gaby/TwgkC/3/ and it works fine
In FF , Opera, Chrome, Safari, IE8.. Tested in
#someid needs to get focus to trigger keypress, if you want your code to get focus immediately after the element is created use the .focus() method
function AppendSpan()
{
$('#mydiv') .append('Some TExt');
//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..
}
Append:
Two methods to trigger the event, (in fact you need to use the contenteditable attribute), not sure if you can accept this situation
1. Wrap an editable span in another outer layer and set its attribute contenteditable="false"
demo js:
function AppendSpan()
{
$('#mydiv').append(' Some TExt');
//Then I want to handle the keypress event on the inserted span
$ ('#someid').keypress(function(event){alert('test');});
}
$(function()
{
$('#mydiv') .keypress(function(event){AppendSpan();});
});
demo html:
2. Let your #mydiv be in a non-editable state when you need to trigger the keyboard event of span
demo js:
function AppendSpan()
{
$('#mydiv').removeAttr('contenteditable') .append('Some TExt');
//Then I want to handle the keypress event on the inserted span
$( '#someid').keypress(function(event){alert('test');});
}
$(function()
{
$('#mydiv'). keypress(function(event){AppendSpan();});
});
demo html: