Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

请看下这段代码中函数的问题

var trs = document.getElementsByTagName('tr');
for(var i = 0;i < trs.length;i++){       
        trs[i].onmouseover = function(){
            this.style.backgroundColor = 'grey';
        }
        trs[i].onmouseout = function(){
            this.style.backgroundColor = 'white';
        }       
}

请问函数中的this为什么不能换成trs[i]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

如果函数中的this换成trs[i],对应的绑定事件触发时,i已经变成trs.length了,这样就不是对应的元素了。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...