【问题标题】:Event listener to dynamically created buttons动态创建按钮的事件监听器
【发布时间】:2020-08-26 09:41:18
【问题描述】:

我有一个按钮,它附加了一个包含几个 div 和按钮的模板。 第一个按钮“btnGenerateResult_0”工作正常可能是因为它在页面加载时存在,而“btnGenerateResult_1”被创建但不起作用。 如何以及在哪里修复事件侦听器并将其附加到这些按钮,我需要四个按钮?

下面的代码在 document.readey function() 中:

$(`#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); 
    }

});

【问题讨论】:

    标签: javascript jquery button events dynamic


    【解决方案1】:

    一种选择是在创建按钮后将事件监听器添加到新创建的按钮:

    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>

    【讨论】:

      猜你喜欢
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多