On (this issue and trs [i]) JavaScript closure for loop execution order

 
.over{
    Background:red;
}
.out{
    Background:white;
}

var trs=document.getElementsByTagName("tr");
for(var i=0;i<trs.length;i++){
    trs[i].onmouseover= function(){
        this.className="over";
    };
   trs[i].onmouseout= function(){
        this.className="out";
    }
}

 

In fact, the process for loop for each TRS [i] is the action performed onmouseover and onmouseout two binding events, not to perform function () {}, for up to execute the entire loop, so i in memory the size has equal length

 

Because each row binding properties of the two events, so when the mouse triggered a row, so things will happen:

Line triggering event of this point itself, function execution

 

Note: If this is not written but trs [i], the result is undefined, because the event is triggered function will first go to i variable, but this time i was in memory of length, so here to write this.

 

For events and perform process binding method, you can look at the following example:

function test() {
    var temp = 10;
    for (var i = 0; i < 5; i++) {
        document.getElementById("p"+i).onclick = function(){
            alert(temp);
        }
    }
    temp = 20;
}
test();

 

Click the pop-up will find temp is 20 instead of 10, which proves the for loop just executed action binding event is triggered when we click event, this time the value of temp is already 20 a. ( this example is to look at other bloggers)

 

Guess you like

Origin blog.csdn.net/xiao_Ray/article/details/81146600