getHref:获取A链接指向(面试题)

来源:互联网 发布:渠道管控管理系统源码 编辑:程序博客网 时间:2024/05/22 06:37

英语专八转前端,在家学习ing。
说说今天面试吧,后台人面,不懂前端。没被录取。
我说说面试题吧;
改写以下代码:

for(var i=0;i<document.getElementsByTagName("a").length;i++){    document.getElementsByTagName("a")[i].onclick=function(){        console.log(this.href)    }}

这道题考性能,先吐槽一下点击链接会跳转页面吧,就假定单纯考试性能;我大脑想的是:用判断代替循环;给父级绑定;

window.onload = function () {            parent.onclick = function (e) {                e.preventDefault();                var target = e.target;                if (target.nodeName.toLowerCase() == "a") {                    console.log(target.href)                }            }    }

但是如果不知道父元素呢?绑定给父元素的父元素,干脆绑定给document,请看以下代码;

    window.onload = function () {        document.onclick = function (e) {            e.preventDefault();            var target = e.target;            if (target.nodeName.toLowerCase() == "a") {                console.log(target.href)            }        }    }

但是其实上一节说过了,用函数包裹起来一个变量doc=document;这样每次调用函数时会自动获取当前的document,而且使用完后会销毁。
其实这样的假设很没有意义,尤其是一个后台程序员在看着所谓标准答案时:

for(var i=0,as=document.getElementsByTagName("a");i<as.length;i++){    as[i].onclick=function(){        console.log(this.href)    }}