JavaScript - onClick to get the ID of the clicked

2018-12-31 14:19发布

How do find the id of the button which is being clicked?

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

function reply_click()
{
}

14条回答
残风、尘缘若梦
2楼-- · 2018-12-31 15:03
<button id="1" onClick="reply_click(this)"></button>
<button id="2" onClick="reply_click(this)"></button>
<button id="3" onClick="reply_click(this)"></button>

function reply_click(obj)
{
var id = obj.id;
}
查看更多
步步皆殇っ
3楼-- · 2018-12-31 15:04

With pure javascript you can do the following:

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);
    };
}​

check it On JsFiddle

查看更多
登录 后发表回答