经典js问题

经典js问题

    var list = document.getElementsByTagName("li");  

    function foo(){  
        for(var i = 0, len = list.length; i < len; i++){  
            list[i].onclick = function(){  
                alert(i + "----" + this.innerHTML);  
            }  
        }  
    }  
    foo(); 

我们会发现运行结果是弹出 list.length,这是因为没有块级作用域造成的,解决办法由几个:

1.使用闭包

var list = document.getElementsByTagName("li");  

function foo(){  
    for(var i = 0, len = list.length; i < len; i++){  
        var that = list[i];  
        list[i].onclick = (function(k){  
            var info = that.innerHTML;  
            return function(){  
                alert(k + "----" + info);  
            };  
        })(i);  
    }  
}  
foo(); 

2.使用闭包

var list = document.getElementsByTagName(“li”);

function foo(){‘use strict’
for(let i = 0, len = list.length; i < len; i++){
list[i].onclick = function(){
alert(i + “—-” + this.innerHTML);
}
}
}
foo();

3.事件委托

var myul = document.querySelector('ul');  
var list = document.querySelectorAll('ul li');  

myul.addEventListener('click', function(ev){  
    var ev = ev || window.event;  
    var target = ev.target || ev.srcElemnt;  

    for(var i = 0, len = list.length; i < len; i++){  
        if(list[i] == target){  
            alert(i + "----" + target.innerHTML);  
        }  
    }  
});  

4.使用jquery的delegate和on进行事件绑定

<script type="text/javascript">  

$("ul").delegate("li", "click", function(){  
    var index = $(this).index();  
        var info = $(this).html();  
    alert(index + "----" + info);  
});  

script>  

<script type="text/javascript">  

$("ul").on("click", "li", function(){  
    var index = $(this).index();  
        var info = $(this).html();  
    alert(index + "----" + info);  
});  

script>

你可能感兴趣的:(javascript,js)