![](/img/trans.png)
[英]How to add class to element created using 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.
}
您還可以在符合標准的瀏覽器中使用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);}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.