Use let small example to achieve the cycle

 

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <ul>
            <li>HTML</li>
            <li>CSS</li>
            <li>JS</li>
            <li>JQ</li>
            < Li > HTML5 </ li > 
            < li > CSS3 </ li > 
            < li > ES6 </ li > 
        </ ul > 
    </ body > 
    < Script > 
        // use let you declare a variable i, i just only in the current round of cycle effectively; var If the declaration of variables, then, is a global variable, it is the final output of 8 
        var List = document.getElementsByTagName ( ' Li ' );
         for (the let I =  0 ; I < List.length; I ++ ) {
            list[i].onmouseover = function(){
                str = list[i].innerText;
                this.innerText += '我是第' + (i+1) + ''
                this.style.fontSize = '22px'
                this.style.color = '#f00'
            }
            list[i].onmouseout = function(){
                this.style.color = 'black'
                this.style.fontSize = '16px'
                this.innerText = str;
            }
        }
        
    </script>
</html>

 

 

In the current work with variable scope only let declarations, {} in one cycle will have a value of i when clickable elements, will obtain the value of i in the current environment, so that the result is a corresponding.

If you do not add a self-executing anonymous function with the var statement, then, for the first cycle will be finished, click on the element of time will perform the bind click event, click the event environment is not i value, this upward along scopes look, i found that the value of the for loop. This time for the cycle has finished, i value of 7, so no matter which button across, the result is 11 pop

 

Guess you like

Origin www.cnblogs.com/rickdiculous/p/12242725.html