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

こ雲淡風輕ζ 提交于 2019-12-31 02:02:12

问题


I want to reduce the code.

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

document.getElementById('dealsButton_1').onclick = one;
document.getElementById('dealsButton_2').onclick = one;
//I  want the above 2 lines of code reduced to one.

A single function for on click on 'dealsButton_*' patterned id elements. How can I do this. The elements are dynamically loaded.


回答1:


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>`;



回答2:


Are you looking for something like this:

function onClick(){
  //single handler
}

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



回答3:


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>



回答4:


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)
 })
});


来源:https://stackoverflow.com/questions/45753375/single-onclick-function-for-buttons-with-a-similar-id-pattern-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!