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

久未见 提交于 2019-12-01 23:05:38

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);
});
<div id="dealsButton_1">one</div>
<div id="dealsButton_2">two</div>

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 = `<div id="dealsButton_1">one</div>
<div id="dealsButton_2">two</div>`;

Are you looking for something like this:

function onClick(){
  //single handler
}

$('[id*="dealsbutton_"]').click(onClick)

Here is a solution where you can choose ID name as u wish without a specific pattern of name.

<html>
  <body>
    <div id="abc">one</div>
    <div id="def">two</div>

    <script type="text/javascript">
      function one() {
       console.log("hai");
      }

      function addOnclickFunc (func, idArray){
        idArray.forEach(function(element) {
          document.getElementById(element).onclick = func;
        })
      }

      addOnclickFunc(one,["abc","def"])
    </script>
  </body>
</html>

you use jQuery with regex for this

$.each( $("button[id^='dealsButton_']"), function () {
 $(this).on('click', function(){
  //code here
 })
});

if want to make the function call names dynamically. pass it as data attribute to button element and call it using eval function

<button id="dealButton_1" data-click="one"></button>

$.each( $("button[id^='dealsButton_']"), function () {
 $(this).on('click', function(){
   var function_call = $(this).attr('data-click')
   eval(function_call)
 })
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!