简体   繁体   中英

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 event to the text box:

 var el = document.createElement('input');
           el.type = 'text';
     
             el.setAttribute("id",'suggest22');  
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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM