js batch monitor - number of closures problem

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
    <style type="text/css">
        p{
            width: 60px;
            height: 60px;
            float: left;
            margin-right: 20px;
            background-color: yellowgreen;
        }
    </style>
</head>
<body>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></P > 
    < P > </ P > 

    < Script type = "text / JavaScript" > 
        var PS = document.getElementsByTagName ( " P " ); 

        // first, IIFE 
        // for (var I = 0; I <PS .length; i ++) {     
        //      (function (m) { 
        //          PS [m] .onclick = function () { 
        //              Alert ( "I'm old" + m + "point me doing !!?"); 
        //          } 
        //      }) (I);
        // } 


        // described second method, is very clever, simple than the first 
        for ( var I=  0 ; i < ps.length; i ++ ) { 
            PS [i] .index = i;     // first number everyone convention called index, will do what is in fact called 
            
            // then set the monitor 
            ps [i] .onclick =  function () { 
                Alert ( " I'm old "  +  the this .index +  " point I doing? !! " ) 
            } 
        } 
    </ Script > 
</ body > 
</ HTML >

 

Guess you like

Origin www.cnblogs.com/xiaobaicai123/p/11464783.html