簡體   English   中英

我們如何在 JavaScript 中為使用 document.createElement() 創建的元素添加焦點等事件?

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

我想在文本框中添加一個焦點事件:

 var el = document.createElement('input');
           el.type = 'text';
     
             el.setAttribute("id",'suggest22');  
el.onfocus = function() {
   // Focused.
}

js小提琴

您還可以在符合標准的瀏覽器中使用addEventListener('focus', function() {... }, false)並在 < IE9 中使用attachEvent('onfocus', function() {... })

此外,您可以使用id屬性作為設置元素的id屬性的快捷方式。

您也不應該混合使用單 ( ' ) 和雙 ( " )。始終使用其中一個。

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

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

演示http://jsfiddle.net/gaby/GN2tP/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM