问题
I'm using this function in order to replace <DIV>New Divs</DIV>
with <BR>
in break lines on contentEditable divs using Safari and Chrome:
$("#form_description").live("keypress", function(e){
if (e.which == 13) {
if (window.getSelection) {
var selection = window.getSelection(),
range = selection.getRangeAt(0),
br = document.createElement("br");
range.deleteContents();
range.insertNode(br);
range.setStartAfter(br);
range.setEndAfter(br);
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
return false;
}
}
});
The problem is that when I'm typing inside an <UL><LI>Something</LI></UL>
and I press the "return" key, I don't want to get a <BR>
, so I can continue whit the list...
How could I create a condition for that function not to work if I'm inside a LI
element?
EDIT WITH MY ANSWER:
Ok, I've managed to do it, but If you have any comment on the code, you're welcome:
$("#form_description").live("keypress", function(e){
if (e.which == 13) {
node = document.getSelection().anchorNode;
nodeName = node.parentNode.nodeName.toLowerCase();
if ((nodeName != "li") && (nodeName != "blockquote")) {
... etc }
回答1:
First, use keyup
as the event name, keypress works only on Firefox.
Second, e.which is not always available. Use e.keyCode primarily, and fall back to e.which:
var code = e.keyCode || e.which;
if (code == 13) {
// your code here..
}
Third, if you need to cancel default events fired in the key-press, you might want to throw in a preventDefault() inside your event handler routine. Make sure it's the first line.
function(e){
e.preventDefault();
..
}
来源:https://stackoverflow.com/questions/6024594/avoid-createelement-function-if-its-inside-a-li-element-contenteditable