确定在div中单击了哪个按钮 [英] Determine which button was clicked inside a div

查看:54
本文介绍了确定在div中单击了哪个按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下HTML代码(无法更改),并且我想编写一个JavaScript代码来确定单击了从A到Z的哪个按钮.知道我该怎么做吗?这是我尝试过的方法,但是我总是得到结果字母".我也可以这样写:

I have the following HTML code (I can't change it) and I want to do a javascript code to determine which button of those from A to Z was clicked. Any idea how I can do this? Here is what I tried, but I always get the result "alphabet". I could also write:

document.getElementById("A").onclick = buton;, 
document.getElementById("B").onclick = buton; 

等在 myMain 函数中,但是有一个简单的解决方案吗?

and so on inside myMain function but is there a simple solution?

<html>
<head>
    <script>
        window.onload = myMain;
        function myMain() {
            document.getElementById("alphabet").onclick = buton;
        }
        function buton() {
            alert(this.id);
        }
    </script>
</head>
<body>
    <div id="alphabet">
        <button id="A">A</button> <button id="B">B</button> <button id="C">C</button> <button id="D">D</button> <button id="E">E</button> <button id="F">F</button> 
        <button id="G">G</button> <button id="H">H</button> <button id="I">I</button> <button id="J">J</button> <button id="K">K</button> <button id="L">L</button> 
        <button id="M">M</button> <button id="N">N</button> <button id="O">O</button> <button id="P">P</button> <button id="Q">Q</button> <button id="R">R</button> 
        <button id="S">S</button> <button id="T">T</button> <button id="U">U</button> <button id="V">V</button> <button id="W">W</button> <button id="X">X</button> 
        <button id="Y">Y</button> <button id="Z">Z</button>
    </div>
</body>
</html>

推荐答案

您可以使用事件对象

window.onload = myMain;

function myMain() {
  document.getElementById("alphabet").onclick = buton;
}

function buton(e) {
  if (e.target.tagName == 'BUTTON') {
    alert(e.target.id);
  }
}

<div id="alphabet">
  <button id="A">A</button>
  <button id="B">B</button>
  <button id="C">C</button>
  <button id="D">D</button>
  <button id="E">E</button>
  <button id="F">F</button>
  <button id="G">G</button>
  <button id="H">H</button>
  <button id="I">I</button>
  <button id="J">J</button>
  <button id="K">K</button>
  <button id="L">L</button>
  <button id="M">M</button>
  <button id="N">N</button>
  <button id="O">O</button>
  <button id="P">P</button>
  <button id="Q">Q</button>
  <button id="R">R</button>
  <button id="S">S</button>
  <button id="T">T</button>
  <button id="U">U</button>
  <button id="V">V</button>
  <button id="W">W</button>
  <button id="X">X</button>
  <button id="Y">Y</button>
  <button id="Z">Z</button>
</div>

这篇关于确定在div中单击了哪个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆