1. Closures: Extend the scope of variables and save values that change at any time
Code:
<ul>
<li><a href= "#" > click on the No. 0 link </a></li>
<li><a href= "#" > click on the 1th link </a></li>
<li><a href= "#" > click on the 2nd link </a></li>
<li><a href= "#" > click on the 3rd link </a></li>
<li><a href= "#" > click on the 4th link </a></li>
</ul>
var links = document.getelementsbytagname (' a ');
Method 1:
function Closuretest (num) {
return function () {
Alert ("You clicked on the" + num + "link");
}
}
for (Var i=0;i<links.length;i++) {
Links[i].onclick = Closuretest (i);
}
Method 2:
for (Var i=0;i<links.length;i++) {
Links[i].onclick = (function (i) {
return function () {
Alert ("You clicked on the" + i + "link");
};
}) (i)
Method 3:
(function (i) {
Links[i].onclick = function () {
Alert ("You clicked on the" + i + "link");
// };
}) (i)
}
JS Closed Package