The problem code is as follows:
//研究点击for循环和单击相应函数的执行顺序问题
window.onload = function(){
//获取所有的超链接
var allA = document.getElementsByTagName("a");
//为每一个超链接绑定一个单击响应函数
for(var i = 0; i < allA.length; i++){
allA[i].onclick = function(){
//正确代码应该是使用this,而不是allA[i],而使用allA[i]就会发生错误
//this:this指的是当前的第i个超链接本身
alert(allA[i]);
return false;
}
}
}
The code of the problem is as follows: Problem recurrence: when the web page finished loading and clicking the button, the corresponding operation (function()) cannot be performed.
Analysis: When the web page is loaded, the for loop is executed, and each hyperlink button is given a click response function. Then the page has loaded and the for loop finished completing. In this case, the 'i' of the for loop is allA.length. When we click the hyperlink button, allA[I] in the binding function is always allA[allA. length], execution fails.
correct:alert(allA[i])---------------->alert(this)。reason:u dont need allA[i]to find hyperlink, 'this' will point to the hyperlink itself.
example again
The problem code is as follows:
var btns =document.getElementsByTagName("button");
for(var i = 0,length = btns.length;i < length; i++){
//if set i < btns.length , every time it should be counted again, so
//it will waste resource. so we define it before.
var btn = btns[i];
btn.onclick = function(){
alert("the" + (i + 1))
}
}
solution 01
var btns =document.getElementsByTagName("button");
for(var i = 0,length = btns.length;i < length; i++){
//if set i < btns.length , every time it should be counted again, so
//it will waste resource. so we define it before.
var btn = btns[i];
btn.index = i;
btn.onclick = function(){
alert("the" + (this.index + 1));
}
}
solution 02:利用闭包
var btns =document.getElementsByTagName("button");
for(var i = 0,length = btns.length;i < length; i++){
//if set i < btns.length , every time it should be counted again, so
//it will waste resource. so we define it before.
(function(i) {
var btn = btns[i];
btn.onclick = function() {
alert("the" + (i + 1));
}
})(i)
}