JavaScript - onClick to get the ID of the clicked button

前端 未结 16 1227
名媛妹妹
名媛妹妹 2020-11-22 05:44

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


16条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 06:27

    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

提交回复
热议问题