javascript - 创建对象的事件监听器
问题描述
我已经使用模板字符串创建了表单节点,但我需要对它们进行更改。我试过.on('DOMNodeInserted')
了,但我没能赶上这个事件。我也尝试使用 Promise,但我不知道它是否可以在带有 Promise 的 html 节点上工作。有没有办法在稍后附加的 html 对象上触发事件侦听器?
这是我的许多尝试之一
$('.body').on('DOMNodeInserted', function(e) {
if($(e.target).children()[0] !== undefined){
let tema = $(e.target).children()[0].id;
tema.onchange = () => {
let el = manage(tema);
console.log(el);
}
}});
我
解决方案
这是一个从动态插入的元素中捕获事件的示例。它使用“事件委托” - 将侦听器附加到父元素以在子元素冒泡 DOM 时捕获来自子元素的事件。
// I've used `container` here but you could use any element
// you like. Just add a change listener to it identifying the
// function that needs to be called when it's triggered
const container = document.querySelector('#container');
container.addEventListener('change', handleChange, false);
const html = `
<form>
<input name="input1" type="text" placeholder="input1" />
<input name="input2" type="text" placeholder="input2"/>
</form>
`;
container.insertAdjacentHTML('beforeend', html);
function handleChange(e) {
// The `event target` is whatever element has caused the change
// listener to trigger. Here I've grabbed the name from the element
// using destructuring and logged it to the console
const { name } = e.target;
console.log(name);
}
<div id="container"></div>
推荐阅读
- python - 如何在 python 3.6 中导入我自己的模块?
- jquery - 使用 formvalidation.io 进行动态复选框验证
- sql - 日期之间的 SQL / Oracle 聚合桶
- swift - insertItemsAt 集合视图崩溃
- drupal - 如何从内联实体表单中获取用户输入数据并在保存 drupal 8 之前对其进行更改
- javascript - 使用箭头键在另一个 div 中移动一个 div
- vba - VBA Outlook Mail Body
- bash - bash/ksh 脚本中的命令调用
- google-chrome - 页面和扩展之间的通信
- mysql - MYSQL:用相同的字段左连接同一张表两次