如何循环浏览javascript中的按钮?

时间:2016-02-23 10:49:17

标签: javascript html5 for-loop button getelementbyid

我的网站上有许多不同的按钮,我想为每个按钮分配不同的任务,目前我正在使用getElementByID逐个引用它们,因为我有很多按钮我最后写了无穷无尽的行代码只是为了引用按钮,有一些java的知识我明白我所做的事情可以用更少的代码使用for循环实现,但我不太清楚如何去做,欢迎任何帮助。

目前我正在引用我的按钮:

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

然后我为每个人分配点击监听器:

Button1Menu.onclick = function() {

     //doing something

  };

有没有更好的方法来实现这一点。

5 个答案:

答案 0 :(得分:3)

启动计数器并继续检查,直到找到不存在的按钮

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

如果需要为所有按钮分配点击事件,则

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

答案 1 :(得分:1)

$('button').on('click',function(){
    alert($(this).attr('id'));
});

现在在click事件中使用$(this) jquery对象

答案 2 :(得分:1)

请尝试此操作(添加的功能doSomething(item)来解释实际使用情况):

    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>

答案 3 :(得分:1)

假设您有一个父元素用于全部或部分按钮:

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

单击事件监听器足以处理所有这些:

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

这称为事件委托,它对你有好处

答案 4 :(得分:0)

jQuery解决方案

$("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>