The buttons below output their numbers in the console when clicked. Fire 1 should output 1, Fire 2 should output 2, and so on.
I am using a for
loop to pass 1–4 to the functions that call fire(n)
, but the output is never what I expect when I click any of the buttons. I tried following an answer to this question, but it is not working for me.
If I use the code I commented out instead of the for
loop, everything works fine. Why will this not work if I use the for
loop?
function fire(n) {
console.log(n);
}
for (var i = 1; i <= 4; ++i) {
$("#fire" + i).on("click", fire(i));
}
/*
$("#fire" + 1).on("click", function(){fire(1)});
$("#fire" + 2).on("click", function(){fire(2)});
$("#fire" + 3).on("click", function(){fire(3)});
$("#fire" + 4).on("click", function(){fire(4)});
*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="fire1">Fire 1</button>
<button id="fire2">Fire 2</button>
<button id="fire3">Fire 3</button>
<button id="fire4">Fire 4</button>