如何找到正在点击的按钮的id ?

<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>

function reply_click()
{
}

当前回答

这是Prateek答案的改进-事件是通过参数传递的,因此reply_click不需要使用全局变量(到目前为止没有人提出这个变量)

函数reply_click(e) { console.log (e.target.id); } <button id="1" onClick="reply_click(event) "“> B1 > < /按钮 <button id="2" onClick="reply_click(event) "“> B2 > < /按钮 <button id="3" onClick="reply_click(event) "“> B3 > < /按钮

其他回答

抱歉,这是一个很晚的回答,但如果你这样做的话,它真的很快:-

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

这将获得单击的任何按钮的ID。

如果你想要在某个地方点击按钮的值,就把它们放在容器中

<div id = "myButtons"> buttons here </div>

并更改代码为:-

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

我希望这对你们有帮助

这是Prateek答案的改进-事件是通过参数传递的,因此reply_click不需要使用全局变量(到目前为止没有人提出这个变量)

函数reply_click(e) { console.log (e.target.id); } <button id="1" onClick="reply_click(event) "“> B1 > < /按钮 <button id="2" onClick="reply_click(event) "“> B2 > < /按钮 <button id="3" onClick="reply_click(event) "“> B3 > < /按钮

虽然晚了8年多,但为了从(我的)HTML中获得动态生成的id,我使用了php循环的索引来增加按钮id。我将相同的索引连接到输入元素的ID,因此我最终得到ID ="tableview1"和button ID ="1",以此类推。

$tableView .= "<td><input type='hidden' value='http://".$_SERVER['HTTP_HOST']."/sql/update.php?id=".$mysql_rows[0]."&table=".$theTable."'id='tableview".$mysql_rows[0]."'><button type='button' onclick='loadDoc(event)' id='".$mysql_rows[0]."'>Edit</button></td>";

在javascript中,我将按钮单击存储在一个变量中,并将其添加到元素中。

function loadDoc(e) {
  var btn = e.target.id;
  var xhttp = new XMLHttpRequest();
  var page = document.getElementById("tableview"+btn).value;
  
  //other Ajax stuff
  }

一般来说,如果将代码和标记分开,事情就更容易保持有序。定义所有元素,然后在JavaScript部分定义应该在这些元素上执行的各种操作。

当调用事件处理程序时,它是在所单击元素的上下文中调用的。标识符this会指向你点击的DOM元素。然后,您可以通过该标识符访问元素的属性。

例如:

<button id="1">Button 1</button>
<button id="2">Button 2</button>
<button id="3">Button 3</button>

<script type="text/javascript">
var reply_click = function()
{
    alert("Button clicked, id "+this.id+", text"+this.innerHTML);
}
document.getElementById('1').onclick = reply_click;
document.getElementById('2').onclick = reply_click;
document.getElementById('3').onclick = reply_click;
</script>
 <button id="1"class="clickMe"></button>

<button id="2" class="clickMe"></button>

<button id="3" class="clickMe"></button>



$('.clickMe').live('click',function(){

var clickedID = this.id;

});