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

前端 未结 4 478
耶瑟儿~
耶瑟儿~ 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:32

    Are you looking for something like this:

    function onClick(){
      //single handler
    }
    
    $('[id*="dealsbutton_"]').click(onClick)
    
    0 讨论(0)
  • 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);
    });
    <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>`;

    0 讨论(0)
  • 2021-01-21 03:45

    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>
    
    0 讨论(0)
  • 2021-01-21 03:45

    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)
     })
    });
    
    0 讨论(0)
提交回复
热议问题