I am a green-hand web programmer trying to binding onclick events functions to a series of components via a for loop and has tested it in chrome browser.
<!DOCTYPE html>
<html>
<head>
<title>Onclick Test</title>
</head>
<body>
<button id="button1">BUTTON</button>
<button id="button2">BUTTON</button>
<button id="button3">BUTTON</button>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
for (var i = 0; i < document.getElementsByTagName('button').length; i++) {
let g = () => console.log(i);
document.getElementsByTagName('button')[i].onclick = g;
g();
}
$(document).ready(() => {
for (var i = 0; i < $('button').length; i++) {
let f = () => console.log(i);
f();
$('button').eq(i).click(f);
}
});
</script>
</body>
</html>
The console log shows that the onclick functions only take in the parameter 3. It seems that the browser has only fetched the loop index i as 3. I am in such a confuse. I wonder how does the onclick function in JavaScript work? And what is the scope for the variable i?
Here is the console log:
OnclickTest.html:13 0
OnclickTest.html:13 1
OnclickTest.html:13 2
OnclickTest.html:23 0
OnclickTest.html:23 1
OnclickTest.html:23 2
OnclickTest.html:13 3
OnclickTest.html:23 3
OnclickTest.html:13 3
OnclickTest.html:23 3
OnclickTest.html:13 3
OnclickTest.html:23 3