简体   繁体   中英

How to loop through buttons in javascript?

I have number of different buttons on my website and I want to assign different task to each button, currently I am referencing them one by one using getElementByID and because I have so many buttons I ended up writing endless lines of codes just to reference the buttons, having some knowledge of java I understand that what I have done could be achieved with less code using for loop but I am not quite sure how to go about doing that, any help is welcomed.

Currently this is how I am referencing my buttons:

    var Button1Menu = document.getElementById("button1menu"); 
    var Button2Menu = document.getElementById("button2menu"); 
    var Button3Menu = document.getElementById("button3menu"); 
    var Button4Menu = document.getElementById("button4menu"); 
    var Button5Menu = document.getElementById("button5menu"); 
    var Button6Menu = document.getElementById("button6menu"); 
    var Button7Menu = document.getElementById("button7menu"); 
    var Button8Menu = document.getElementById("button8menu"); 
    var Button9Menu = document.getElementById("button9menu"); 
    .....
    .....
    .....
    var Button43Menu = document.getElementById("button43menu"); 

and then I am assigning click listener to each one:

Button1Menu.onclick = function() {

     //doing something

  };

Is there a better way of achieving this please.

initiate a counter and keep checking till you get a button that doesn't exist

var counter = 1;
var button  = document.getElementById( "button" + counter + "menu" );

while ( button )
{
   button.addEventListener("click", function(){
      //do something here
   });

   button  = document.getElementById( "button" + ( ++counter ) + "menu" );
}

if all the buttons needs to be assigned a click event then

var buttons = document.querySelectorAll( "button[id^='button'][id$='menu']" );
for ( var counter = 0; counter < buttons.length; counter++)
{
    buttons[counter].addEventListener("click", function(){
      //do something here
   });
}
$('button').on('click',function(){
    alert($(this).attr('id'));
});

Now inside the click event use the $(this) jquery object

Please, try this ( added function doSomething(item) to explain a real usage ):

    function doSomething(item) {
        switch (item.id) {
            case 'button3menu': 
                // Make this button do something, only it. For example: 
                alert('Hey, you are pressing me!');
                break;
            default:
                // Make all the button's whose id is not contemplated as a case value 
                alert('My id is: ' + item.id);
                break;
    }}

        <script>
        (function()
        {
            var num = 4;
            for (var i = 0; i < num; i++)
            {
                var elem = document.createElement('button');
                elem.id = "button" + i + "menu";
                elem.innerHTML = "button" + i;
                document.body.appendChild(elem)

                elem.addEventListener('click', function(){doSomething(this)});
            }
        })()
        </script>

Assuming that you have a parent element for all or some of your buttons:

<div id="parent">
<button id="button1menu">button</button>
<button id="button2menu">button</button>
<button id="button3menu">button</button>
<button id="button4menu">button</button>
<button id="button5menu">button</button>
<button id="button6menu">button</button>
</div>

A single click event listener is enough to handle all of them:

document.getElementById("parent").addEventListener("click", function(e) {
     // e.target is the clicked element
    //check if button1menu has been clicked
    if(e.target && e.target.id == "button1menu") {
        alert(e.target.id + " was clicked");
    }

    //check if button2menu has been clicked
    if(e.target && e.target.id == "button2menu") {
        alert(e.target.id + " was clicked");
    }

  //etc
 });

You can experiment more in this fiddle

This is called event delegation and its good for you

jQuery solution

 $("button[id^='button']").on('click', function() { console.log($(this).attr('id')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="button1menu">button</button> <button id="button2menu">button</button> <button id="button3menu">button</button> <button id="button4menu">button</button> <button id="button5menu">button</button> <button id="button6menu">button</button> 

If someone still looking for solution - create collection using document.querySelectorAll, and then via loop assign index for every button. After that you can put in each case functionality that you need. It works for simple tasks.

For example below, i have three buttons, by clicking any of them background color will change:

HTML:

<div id="page-container">
  <button type="button" class="btn btn-red">red</button>
  <button type="button" class="btn btn-green">green</button>
  <button type="button" class="btn btn-blue">blue</button>
  <script src="buttonCollection.js"></script>
</div>

JS:

let pageContainer = document.getElementById('page-container')
let buttons = document.querySelectorAll('.btn')
let index = undefined;

for (let i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener('click', function () {
    index = i;
    switch (index) {
        case 0:
          pageContainer.style.backgroundColor = "red"; 
          break;
      
        case 1:
          pageContainer.style.backgroundColor = "green";
          break;
      
        case 2:
          pageContainer.style.backgroundColor = "blue";
          break;
      
        default:
          pageContainer.style.backgroundColor = "bisque";
          break;
      }
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM