In my work these days encountered a problem, Google a bit to find a solution, but in English, I simply translated so that more people can read
The translation is as follows:
I have an editable div, and there's an editable span within the Div, and I want span to be able to respond to keyboard events,
Here is the test JS code:
Copy Code code as follows:
$ (function ()
{
$ (' #someid '). KeyPress (function (event) {alert (' Test ');});
});
here is the test HTML code:
Copy Code code as follows:
<div id= "Mydiv" contenteditable= "true" >
Editable Follows:<span id= "Someid" contenteditable= "true" >some text</span>
</div>
If you test in a browser, you will see that when you some text on the press key, there is no ' Test ' pop-up, I know this problem occurs because the event was sent from the parent node div of span, so span did not trigger the event, but also because span has no focus, so I want someone to help me find the solution.
Finally, a kind-hearted person helped solve the problem.
Solution code for your problem I've submitted it to http://jsfiddle.net/gaby/TwgkC/3/and I'm working properly.
In FF, Opera, Chrome, Safari, IE8. Test in
#someid需要获得焦点才能触发keypress, if you want your code to get focus immediately after the element is created. Focusing () method
Copy Code code as follows:
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.
}
Additional:
Two methods to trigger the event (in fact, you need to use the Contenteditable property), not sure if you can accept this
1, wrap an editable span in another's outer layer, and set its properties contenteditable= "false"
Demo JS:
Copy Code code as follows:
function Appendspan ()
{
$ (' #mydiv '). Append (' <span contenteditable= false ' ><span id= ' Someid ' contenteditable= ' true ' >some TExt </span></span> ');
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:
Copy Code code as follows:
<div id= "Mydiv" contenteditable= "true" >
Editable follows:
</div>
2, let your #mydiv in a non edit state, when you need to trigger the span of keyboard events
Demo JS:
Copy Code code as follows:
function Appendspan ()
{
$ (' #mydiv '). Removeattr (' contenteditable '). 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) {alert (' Test ');});
}
$ (function ()
{
$ (' #mydiv '). KeyPress (function (event) {Appendspan ();});
});
Demo HTML:
Copy Code code as follows:
<div id= "mydiv" contenteditable= "true" >
Editable follows:
< /div>