简体   繁体   English

动态创建按钮的事件监听器

[英]Event listener to dynamically created buttons

I have a button that append a template containing few divs and buttons.我有一个按钮 append 一个包含几个 div 和按钮的模板。 The first button "btnGenerateResult_0" works fine probably because it exists when the page loads, while "btnGenerateResult_1" gets created but doesn't work.第一个按钮“btnGenerateResult_0”工作正常可能是因为它在页面加载时存在,而“btnGenerateResult_1”被创建但不起作用。 How and where can I fix the event listener and attach it to these buttons, I need four buttons?如何以及在哪里修复事件侦听器并将其附加到这些按钮,我需要四个按钮?

The bellow code is inside a document.readey function():下面的代码在 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); 
    }

}); });

One option is to add the event listener to the newly created button after you have created it:一种选择是在创建新按钮后将事件侦听器添加到它:

 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>

Another option, which might scale better, is to use event delegation .另一种可能更好地扩展的选项是使用事件委托 It consists of adding a single event listener to the parent or any common ancestor for all those buttons.它包括将单个事件侦听器添加到所有这些按钮的父级或任何公共祖先。 The click event will then bubble app and you can use e.target to find out which button the event originated from:然后单击事件将冒泡应用程序,您可以使用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>

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

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