为什么当我点击我的按钮时,控制台日志中总有100个?我怎么解决这个问题?
function SampleFunction(param){
console.log(param);
}
for (i = 0; i < 100; i++) {
$("#btn-" + i).on('click',function(e){
SampleFunction(i);
});
}
答案 0 :(得分:0)
使用let
关键字
for (let i = 1; i < 9; i++) {
$("#btn-" + i).on('click',function(e){
SampleFunction(i);
});
}
答案 1 :(得分:0)
纯粹的js方法
let allButtons = document.getElementsByTagName('button');
for(i=0;i<allButtons.length;i++) {
allButtons[i].onclick = getPosition;
}
function getPosition() {
let position = Array.from(allButtons).indexOf(this) + 1;
console.log(`you clicked button at position ${position}`)
}
<button id="button-1">1</button>
<button id="button-2">2</button>
<button id="button-3">3</button>
<button id="button-4">4</button>