下面的代碼中,HTML定義了五個按鈕,JS為五個按鈕綁了click事件,然而我沒通過document.getElementById獲取每一個button元素,為什么這樣事件也能綁定成功?<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>test_btn</title> <style type="text/css"> button {padding: 5px 10px;} </style></head><body> <button id="btn">alert btn</button> <button id="btn1">alert btn1</button> <button id="btn2">alert btn2</button> <button id="btn3">alert btn3</button> <button id="btn4">alert btn4</button></body><script type="text/javascript"> btn.onclick = function () { alert("btn"); } btn1.onclick = function () { alert("btn1"); } btn2.onclick = function () { alert("btn2"); } btn3.onclick = function () { alert("btn3"); } btn4.onclick = function () { alert("btn4"); }</script></html>
為什么JS不通過ID獲取元素也能綁定事件?
ibeautiful
2018-09-14 09:41:37