如何找到正在点击的按钮的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()
{
}

当前回答

按钮1按钮2按钮3

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;

其他回答

按钮1按钮2按钮3

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;

如果您不想传递任何参数给onclick函数,只需使用event。目标获取被单击的元素:

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

function reply_click()
{
    // event.target is the element that is clicked (button in this case).
    console.log(event.target.id);
}

使用纯javascript,你可以做到以下几点:

var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i < buttonsCount; i += 1) {
    buttons[i].onclick = function(e) {
        alert(this.id);
    };
}​

检查它在JsFiddle

虽然晚了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: 我知道有点晚了,但也许对未来的人有帮助:

在HTML部分:

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

在Javascipt控制器中:

function reply_click()
{
    alert(event.srcElement.id);
}

这样,我们就不必在调用javascript函数时绑定Element的“id”。