简体   繁体   English

将事件侦听器添加到动态创建的元素

[英]Add Event Listener to Dynamically Created Element

I need to add a new event listener to a dynamically created element and I cannot get the listener to attach.我需要向动态创建的元素添加一个新的事件侦听器,但我无法附加该侦听器。

I attempted this method with no success: add event listener on elements created dynamically我尝试了这种方法但没有成功: 在动态创建的元素上添加事件侦听器

 b[0] = document.createElement("INPUT");
 b[0].name = "dt";
 b[0].type = "text";
 b[0].value = "YYYY-MM-DD HH:MM:SS";
 b[0].addEventListener('focus', removeVal);
 b[0].addEventListener('blur', addDTFormat);
 b[0].className = "fields";

Below is the screenshot from Chrome dev tools.下面是 Chrome 开发工具的屏幕截图。 I have the add listener method with the correct parameters, but in the properties pane the onblur and onfocus events are null for this element.我有带有正确参数的添加侦听器方法,但在属性窗格中,该元素的onbluronfocus事件是 null。

在此处输入图像描述

It should be focus and blur :它应该是focusblur

b[0].addEventListener('focus', removeVal);
b[0].addEventListener('blur', addDTFormat);

However IE's attachEvent requires on prefix.但是 IE on attachEvent需要前缀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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