Tag: HTTPS BSP knows code this keyword LAN TPS color ack
The following code, change this to rows[i] why doesn't it work?
VarRows=Document.getElementsByTagName("TR");For(VarI=0;I<Rows.Length;I++) {rows[i]. Onmouseover=function () {this.< Span class= "NX" >style. Backgroundcolor= "#f2f2f2" }; rows[i]. Onmouseout=function () {this.< Span class= "NX" >style. Backgroundcolor= "#fff" };
/span>
Zheng
Links: https://www.zhihu.com/question/30759173/answer/49334835
Source: Know
Copyright belongs to the author, please contact the author for authorization.
Look at this function alone.
function () { rows[i].style.backgroundColor = ‘#f2f2f2‘;};
This type of anonymous function defined within the loop, Rows[i] I holds the last result of the external loop variable I, which is rows.length for this loop. and Rows[rows.length] does not exist (the last item in the array is rows[rows.length-1]).
If you want the function to correspond to the list item one by one, you can save the I once using a closure, which is the case:
rows[i].onmouseover = (function (n) { return function () { rows[n].style.backgroundColor = ‘#f2f2f2‘; }}(i));
You can also do this:
for (var i = 0; i < rows.length; i++) {rows[i].index = i; Rows[i].onmouseover = function () {Rows[this.index].style.backgroundcolor = ' #f2f2f2 '; }}//saves the value of I by adding property index to the corresponding item
< Span class= "NX" >< Span class= "o" > < Span class= "p" >
What is the scope of traversing an element-bound event, why use the This keyword, and simply using the element itself?