single onclick function for buttons with a similar id pattern - JavaScript

前端 未结 4 529
耶瑟儿~
耶瑟儿~ 2021-01-21 03:24

I want to reduce the code.

function one() {
 console.log(\"hai\");
}

document.getElementById(\'dealsButton_1\').onclick = one;
document.getElementById(\'dealsBu         


        
4条回答
  •  没有蜡笔的小新
    2021-01-21 03:43

    You can use querySelectorAll and the selector [id^=dealsButton_] to add the event listener in a single line - see demo below:

    function one() {
     console.log("hai");
    }
    
    Array.prototype.forEach.call(
      document.querySelectorAll('[id^=dealsButton_]'), function(e) {
      e.addEventListener('click', one);
    });
    one
    two

    If the markup is dynamically loaded you can base it on a static element like this:

    function one() {
      console.log("hai");
    }
    
    document.addEventListener('click', function(e) {
      if (e.target && /^dealsButton_/.test(e.target.id))
        one();
    })
    
    // dynamically add
    document.body.innerHTML = `
    one
    two
    `;

提交回复
热议问题