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

当前回答

一般来说,如果将代码和标记分开,事情就更容易保持有序。定义所有元素,然后在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>

其他回答

如果您不想传递任何参数给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);
}

这是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 > < /按钮

(我认为id属性需要以字母开头。可能是错的。)

你可以选择事件委托……

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

function reply_click(e) {
    e = e || window.event;
    e = e.target || e.srcElement;
    if (e.nodeName === 'BUTTON') {
        alert(e.id);
    }
}

...但这要求您对古怪的事件模型相对熟悉。

您需要将ID作为函数参数发送。这样做:

<button id="1" onClick="reply_click(this.id) "“> B1 > < /按钮 <button id="2" onClick="reply_click(this.id) "“> B2 > < /按钮 <button id="3" onClick="reply_click(this.id) "“> B3 > < /按钮 <脚本type = " text / javascript”> 函数reply_click (clicked_id) { 警报(clicked_id); } > < /脚本

这将发送ID This。Id为clickked_id,可以在函数中使用。在这里看到它的行动。

虽然晚了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
  }