Typescript Notes0:显示点击的是第几个按钮

Typescript Notes0:显示点击的是第几个按钮

TS

<button class="btntest" @click="btntest">click me</button> <button class="btntest" @click="btntest">click me</button> <button class="btntest" @click="btntest">click me</button> const btntest = () => { let btn = document.getElementsByClassName("btntest"); // let btn2 = <HTMLButtonElement>document.getElementById("newTicket"); console.log(btn); console.log(btn.length); for (let i = 0; i < btn.length; i++) { let element: HTMLElement = document.getElementsByClassName('btntest')[i] as HTMLElement; element.onclick = () => { console.log(`这是第${i + 1}个按钮`); } } }

JS参考

<body> <button>click me</button> <button>click me</button> <button>click me</button> <button>click me</button> <button>click me</button> <script> // 获取触发事件的元素 var btn = document.getElementsByTagName("button"); // 绑定点击事件 // 一 for(var i=0;i<btn.length;i++){ (function(i){ btn[i].onclick=function(){ console.log(`这是第${i+1}个按钮`); } })(i); } // 二 for(let i=0;i<btn.length;i++){ btn[i].onclick=function(){ console.log(`这是第${i+1}个按钮`); } } </script> </body>