我已经用模板字符串创建了表单节点,但是我需要在更改时进行操作。
我已经尝试过.on('DOMNodeInserted')
,但没有设法赶上这次活动。我也尝试过与Promise一起工作,但是我不知道它是否可以在带有Promotes的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);
}
}});
我
答案 0 :(得分:0)
这是从动态插入的元素捕获事件的示例。它使用"event delegation"-将侦听器附加到父元素,以在子元素冒起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>