First we need an HTML structure
<div >
<ul>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
</ul>
</div>
We go through all of the UL under the Li and add click events, generally we will add the click event in the For loop, but the result is not the same as we expect, then is why???
Next, look at our JS code.
var li = document.getelementsbytagname (' li ');
for (var i = 0;i<li.length;i++) {
(function (Index) {
li[i].addeventlistener (' click ', Function (e) {
Alert (' I am Link # ' + Index);
},false);
}) (i)
}
We've achieved!!!.
This is the effect we want to hit the corresponding index of the corresponding li.
Let's talk about the implementation process.
(function () {/* code */} ()); This is recommended (
function () {/* code */}) ()//But this is also available.
This is my adjustment function or the self execution function;
In essence, we use the principle of closure to achieve the pop-up index, we set the function to pass a parameter index, that is, our index I, in the function of the implementation of the closure,
The index will remain in the scope block so that when we click on it, we will invoke the indexes stored in the function domain name to achieve the function we need;
We have a few simple examples
function num () {
var i = 0;
return function () {
console.log (i++);
}
}
var counter = num ();
Console.log (counter ()); 0 Console.log (counter ()); ??
var counter1 = (function () {
var i = 0;
return {
get:function () {return
i;
},
Set:function (val) {
i = val;
},
increment: function () {return
++i
}}
}
());
Console.log (counter1);
Console.log (Counter1.get ()); ?
Console.log (Counter1.set (3));//?
Console.log (Counter1.increment ());//?
Console.log (Counter1.increment ());//?
Console.log (counter1);
Console.log (Counter1.get ()); 0
Console.log (counter1.set (3));/3
Console.log (Counter1.increment ());//4
Console.log ( Counter1.increment ()); 5
The above is a small set to introduce the JS Traverse ul under the Li click on the index to pop Li, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!