最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to loop through buttons in javascript? - Stack Overflow

programmeradmin4浏览0评论

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 weled.

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.

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 weled.

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.

Share Improve this question edited Feb 23, 2016 at 11:03 Nishat Lakhani 7311 gold badge8 silver badges20 bronze badges asked Feb 23, 2016 at 10:49 HenryHenry 1,0422 gold badges19 silver badges47 bronze badges 7
  • 2 use event delegation – Raja Sekar Commented Feb 23, 2016 at 10:51
  • How is "Doing something" differing depending on the clicked button? – Teemu Commented Feb 23, 2016 at 10:54
  • Hi @Teemu what do you mean? – Henry Commented Feb 23, 2016 at 11:03
  • Hi @RajaSekar please can you show me an example. – Henry Commented Feb 23, 2016 at 11:04
  • What is the difference between the click handlers of the buttons? Are they totally diffrerent, or are they mostly doing the same task, just having some slightly varying part? – Teemu Commented Feb 23, 2016 at 11:13
 |  Show 2 more ments

6 Answers 6

Reset to default 4

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./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;
      }
    })
}
发布评论

评论列表(0)

  1. 暂无评论