为许多按钮注册事件处理程序

时间:2014-01-08 08:33:00

标签: javascript html

我正在创建一个包含12个以上按钮的计算器,包括数字和算术运算。我必须为每个按钮单独编写document.getElementById("").value。还有其他选择吗?

    <form>
<input type="text"/>
<table>
<tr>
<td> <button id ="button1">1</button></td>
<td> <button id="button2">2</button></td>
<td> <button id="button3">3</button></td>
<td> <button id="button4">4</button></td>
</tr>
<tr>
<td> <button id ="button5">5</button></td>
<td> <button id="button6">6</button></td>
<td> <button id="button7">7</button></td>
<td> <button id="button8">8</button></td>
</tr>
<tr>
<td> <button id ="button9">9</button></td>
<td> <button id="button0">0</button></td>
<td> <button id="button+">+</button></td>
<td> <button id="button-">-</button></td>
</tr>
<tr>
<td> <button id ="button*">*</button></td>
<td> <button id="button/">/</button></td>
<td> <button id="button=">=</button></td>
<td> <button id="buttonc">C</button></td>
</tr>
</table>
</form>

5 个答案:

答案 0 :(得分:1)

var buttons = document.getElementsByTagName("button");

for (i=0;i<buttons.length;i++) buttons[i].onClick = function{ ... };

如果您有更多不应受影响的按钮,则将某些类放入所涉及的按钮并按类名搜索

答案 1 :(得分:1)

试试这个:

var buttonList = document.getElementsByTagName("button");

for(var i=0; i < buttonList.length; i++){
    buttonList[i].addEventListener("click", function() { 
        switch (buttonList[i].id) {
            case "button1":
            // call function for button1 here
            break;
            case "button2":
            // call function for button2 here
            break;
        }
    });

}

答案 2 :(得分:1)

可以将所有计算器关键字{1,2,3,4 .. + - / *}保存在数组和const“按钮”中并循环访问数组并说出

var arr= {"1", "2", "3" .. "*", "/" };

 for(var i =0; i<arr.length; i++){ 
  var element = document.getElementById("button"+arr[i]);
  if(element !=undefined){
        element.value(arr[i]) ;
    /*can add onclick event etc here also..
        element.onclick  = function() {}
     */
    }  
   }

答案 3 :(得分:1)

只需定义一个方法并将其分配给所有按钮

<td> <button id ="button1" onclick=ButtonClick(this)>1</button></td>
<td> <button id="button2" onclick=ButtonClick(this)>2</button></td>


function ButtonClick(Sender)
{
var element = document.getElementById(sender.id);
//now do any thing with this element
}

答案 4 :(得分:1)

检查IE,因为IE不支持addEventListener

var buttonList = document.getElementsByTagName("BUTTON");

for(var i=0; i < buttonList.length; i++){
    var el = buttonList[i];
    if (el.addEventListener) {
        el.addEventListener('click', btnClick, false);  //For non-IE browsers
    } else if (el.attachEvent)  {
        el.attachEvent('onclick', btnClick); //For IE
    }
}

function btnClick() {

}