首页 > 解决方案 > 创建对象的事件监听器

问题描述

我已经使用模板字符串创建了表单节点,但我需要对它们进行更改。我试过.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);
    }
}});

标签: javascript

解决方案


这是一个从动态插入的元素中捕获事件的示例。它使用“事件委托” - 将侦听器附加到父元素以在子元素冒泡 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>


推荐阅读