开发者

Javascript: dynamically add onkeypress event in ie

开发者 https://www.devze.com 2022-12-08 09:49 出处:网络
I am trying to add an onkeypress event to a dynamically created p element. This works fine in Firefox, Opera, and Chrome, but not in IE.

I am trying to add an onkeypress event to a dynamically created p element. This works fine in Firefox, Opera, and Chrome, but not in IE.

My code:

function newParagraphAfter(elem)
{
 blockElemId++;
 newPara = document.createElement("p");
 newPara.id = 'block_' + blockElemId;
 newPara.innerHTML = "Edit Here!";
开发者_如何学编程 elem.parentNode.insertBefore(newPara, elem.nextSibling);
 document.getElementById('block_' + blockElemId).contentEditable = 'true';
 document.getElementById('block_' + blockElemId).focus();
 document.getElementById('block_' + blockElemId).onkeypress = function(event){return editKeypress(this, event)};
 document.getElementById('block_' + blockElemId).onkeydown = function(event){return editKeydown(this, event)};
 document.getElementById('block_' + blockElemId).onblur = function(){deleteIfBlank(this);};
}

Adding the id works in all browsers, and adding innerHTML also works. A test, of changing the background colour (document.getElementById('block_' + blockElemId).style.backgroundColor = "#666"; also worked in all browsers.

However, the lines adding onkeypress, onkeydown and onblur events, and also the .focus() line do not work in IE.

Thank you in advance for any help,

Nico

UPDATE:

I would prefer not to have to use jquery if it can be avoided, simply because I like to be able to modify all of the code in my projects, and not use any 3rd party libraries. I would also have to learn a completely new way of coding, which I would rather not do if it can be avoided.

The contenteditable = 'true' line works perfectly.


Have a look at this: http://jsbin.com/uhiyi

Works fine in IE 8...

0

精彩评论

暂无评论...
验证码 换一张
取 消