开发者

How can we add events like on focus to an element created using document.createElement() in JavaScript?

I would like to add an on focus e开发者_如何学Govent to the text box:

 var el = document.createElement('input');
           el.type = 'text';
     
             el.setAttribute("id",'suggest22');  


var el = document.createElement('input');
el.type = 'text';
el.setAttribute('id','suggest22');

el.onclick = function(){alert(this.id);} 

demo http://jsfiddle.net/gaby/GN2tP/


el.onfocus = function() {
   // Focused.
}

jsFiddle.

You could also use addEventListener('focus', function() { ... }, false) in standards compliant browsers and attachEvent('onfocus', function() { ... }) in < IE9.

Also, you can use id property as a shortcut to setting the element's id attribute.

You also shouldn't mix single (') and double ("). Use one or the other, consistently.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜