如何在Javascript中按下按钮的名称?

时间:2018-05-04 12:13:30

标签: javascript arrays button

我有2个<div>个至少81个按钮,都有相同的类,但它们有不同的ID和名称。我试图弄清楚如何提醒当前按下的按钮的名称。

3 个答案:

答案 0 :(得分:0)

&#13;
&#13;
function runMe(e){
  return function(){
    console.log(e.getAttribute("id"));
  }
}

var eles = document.getElementsByClassName("myButton")
Array.prototype.forEach.call(eles,function(ele){
  ele.onclick = runMe(ele);
})
&#13;
<button id="a1" class="myButton">A1</button>
<button id="b2" class="myButton">B2</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以在点击处理程序功能中使用this.name尝试以下方式:

var btns = document.querySelectorAll('button');
btns.forEach(function(btn){
  btn.addEventListener('click', function(){
    console.log('Name of the cliked button is:', this.name)
  })
})
<div>
  <button type="button" id="btn1" name="btnName1">Button 1</button>
  <button type="button" id="btn2" name="btnName2">Button 2</button>
 
  <!--------- More Buttons--------->
</div>
<div>
  <!--------- More Buttons--------->
 
  <button type="button" id="btn48" name="btnName48">Button 48</button>
  <button type="button" id="btn49" name="btnName49">Button 49</button>
  <button type="button" id="btn50" name="btnName50">Button 50</button>
  
  <!--------- More Buttons--------->
</div>

答案 2 :(得分:0)

获取具有相同类名的所有按钮,并为每个按钮分配click事件侦听器,以便在单击按钮时调用侦听器:

function btnClick(){
 console.log(this.id + " " + this.name);
}

var allButtons = document.getElementsByClassName('myButton');
for(i=0; i<allButtons.length; i++){
   allButtons[i].addEventListener('click', btnClick);
}
<button id="1" class="myButton" name='name1'>B1</button>
<button id="2" class="myButton" name='name2'>B2</button>
<button id="3" class="myButton" name='name3'>B2</button>
<button id="4" class="myButton" name='name4'>B2</button>
<button id="5" class="myButton" name='name5'>B2</button>