如何找到正在点击的按钮的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 > < /按钮

其他回答

 <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;

});

按钮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;

(我认为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);
    }
}

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

你可以简单地这样做:

<input type="button" id="1234" onclick="showId(this.id)" value="click me to show my id"/>
<script type="text/javascript">
   function showId(obj) {
        var id=obj;
        alert(id);
   }

这将记录被单击元素的id: addFields。

<button id="addFields" onclick="addFields()">+</button>

<script>

function addFields(){ 
    console.log(event.toElement.id)
}

</script>