What is the scope of traversing an element-bound event, and why use the This keyword instead of just using the element itself?

Source: Internet
Author: User

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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.