for循环和单击相应函数的执行顺序问题

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)
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值