我有一个按钮,该按钮附加了包含几个div和按钮的模板。第一个按钮“ btnGenerateResult_0”工作正常,可能是因为页面加载时该按钮存在,而“ btnGenerateResult_1”已创建但不起作用。如何以及在何处修复事件侦听器并将其附加到这些按钮,我需要四个按钮?
下面的代码在document.readey函数()中:
$(`#btnGenerateResult_${active}`).click(function ()
{
var newrow = "";
for (var i = 1; i < TablesObj[activeTableObj[active]].length; i ++ )
{
newrow = "";
newrow= "<tr><td>" + TablesObj[activeTableObj[active]][i][0] +
"</td><td>" + TablesObj[activeTableObj[active]][i][3] +
"</tr>";
$(`#resultTableMain_${active}`).append(newrow);
}
});
一个选项是在创建按钮之后将事件监听器添加到新创建的按钮中:
const container = document.getElementById('container');
function handleButtonClicked(e) {
console.log(`Button ${ e.target.textContent } clicked!`);
}
Array.from(container.children).forEach((button) => {
button.onclick = handleButtonClicked;
});
setTimeout(() => {
const newButton = document.createElement('BUTTON');
newButton.textContent = 'C';
container.appendChild(newButton);
// Add the event listener to this new button as well:
newButton.onclick = handleButtonClicked;
}, 2000);
<div id="container">
<button>A</button>
<button>B</button>
</div>
另一个可能会更好扩展的选项是使用event delegation。它包括为所有这些按钮向父级或任何公共祖先添加一个事件侦听器。然后,单击事件将使应用程序冒泡,您可以使用e.target
找出事件源自哪个按钮:
const container = document.getElementById('container');
container.onclick = (e) => {
if (e.target.tagName !== 'BUTTON') {
console.log('Something else clicked...');
return;
}
console.log(`Button ${ e.target.textContent } clicked!`);
};
setTimeout(() => {
// See how this works with dynamically created buttons as wel, withiout adding the
// event listener to each of them individually. However, the event might be
// triggered from undesired elements as well (click in the space between the
// buttons), so you need to check for that, as you can see above.
const newButton = document.createElement('BUTTON');
newButton.textContent = 'C';
container.appendChild(newButton);
}, 2000);
<div id="container">
<button>A</button>
<button>B</button>
</div>