0

Why when I click on my buttons there are always 100 in console log? And how I can fix this?

function SampleFunction(param){
    console.log(param);
}

for (i = 0; i < 100; i++) {
    $("#btn-" + i).on('click',function(e){
        SampleFunction(i);
    });
}
  • try something like this `$("#btn-" + i).on('click', SampleFunction );`, than use event.target in the function like this `function SampleFunction(e){ elem = e.target; console.log( elem.id ); }` – Hsueh Ming-Fang Nov 30 '17 at 06:35

2 Answers2

0

use let keyword

for (let i = 1; i < 9; i++) {
    $("#btn-" + i).on('click',function(e){
        SampleFunction(i);
    });
}
Sudarpo Chong
  • 608
  • 4
  • 12
0

Pure js approach

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>
Rajkumar Somasundaram
  • 1,225
  • 2
  • 10
  • 20