I encountered a problem in my work over the past few days. I have an editable div and an editable span in the DIV. I want to make the span respond to the keyboard, how can I achieve this? I encountered a problem in my work over the past few days. google found a solution, but it is in English, let more people understand it through simple translation.
The translation is as follows::
I have an editable p and an editable span in the DIV. I want the span to respond to Keyboard Events,
Here is the JS Code for testing:
The Code is as follows:
$ (Function ()
{
$ ('# Someid'). keypress (function (event) {alert ('test ');});
});
Here is the test html code:
The Code is as follows:
Editable follows: Some TEXT
If you test in a browser, you will see that when you press the key on Some TEXT, the 'test' pop-up box does not appear, I know the cause of this problem is that the event is sent from span's parent node p, so span does not trigger the event, and of course it is also caused by span's lack of focus, so I want someone to help me find a solution.
Finally, I was able to help solve this problem.
Solution code for your problem I have submitted to the http://jsfiddle.net/gaby/TwgkC/3/ and work fine
Test in FF, Opera, Chrome, Safari, IE8...
# Someid needs to get the focus to trigger keypress. If you want your code to get the focus, use the. focus () method immediately after the element is created.
The Code is as follows:
Function AppendSpan ()
{
$ ('# Myp'). 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 are used to trigger the event (in fact, the contenteditable attribute must be used). you are not sure whether you can accept this situation.
1. Wrap one editable span on the outer layer of the other and set its attribute contenteditable = "false"
Demo js:
The Code is as follows:
Function AppendSpan ()
{
$ ('# Myp'). append ('some text ');
// Then I want to handle the keypress event on the inserted span
$ ('# Someid'). keypress (function (event) {alert ('test ');});
}
$ (Function ()
{
$ ('# Myp'). keypress (function (event) {AppendSpan ();});
});
Demo html:
The Code is as follows:
Editable follows:
2. Keep your # myp uneditable. When you need to trigger a span keyboard event
Demo js:
The Code is as follows:
Function AppendSpan ()
{
$ ('# Myp'). removeAttr ('contenteditable'). append ('some text ');
// Then I want to handle the keypress event on the inserted span
$ ('# Someid'). keypress (function (event) {alert ('test ');});
}
$ (Function ()
{
$ ('# Myp'). keypress (function (event) {AppendSpan ();});
});
Demo html:
The Code is as follows:
Editable follows: