`
鹤惊昆仑
  • 浏览: 223681 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

两道Javascript面试题

    博客分类:
  • web
阅读更多
//实现点击第i个div时仅alert该div对应的i值;
var divs = document.getElementsByTagName("div");
for(var i=0;i<divs.length;i++){
    divs[i].onclick =(function(i){
        return function(e){
            alert(i);
            window.event ? window.event.cancelBubble = true : e.stopPropagation();
        }
    })(i)
}
//考察this绑定。
function test(){
    this.msg = "hi";
    msg ="hello";
    this.test = function(){
       this.msg = "yaya";
       msg = "haha"
       alert(this.msg);
    }
    return this;
}
new test().test(); //yaya
test().test();//haha


2009-6-26日更新:今天偶然看到第一题另外的解法,确实不错:http://xkr.us/js/closures
function setListeners(elements) {
    for (var i=0;i<elements.length;i++) {
        elements[i].idx=i;
        elements[i].onclick=function () { alert(this.idx); };
    }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics