javascript - 点击ul下面的li,弹出当前li的index

这个是之前面试的一道题,当时给的答案是类似下面这种:

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

for(i = 0;i<nodes.length;i+= 1){

        nodes[i].onclick = (function(i){

                  return function() {

                     console.log(i);

                  } 

        })(i);

}

然后回来网上搜了搜,结果发现答案基本就是这一种,当时那个面试官对我这答案感觉不满意,问我还有别的方法实现么,我说不知道= =

这里问问大家,要是你,你会怎么回答这到问题呢


慕斯王
浏览 652回答 1
1回答

森林海

方式1. 使用闭包。var ul = document.getElementsByTagName("ul")[0];&nbsp;&nbsp;var list = ul.getElementsByTagName("li");&nbsp;&nbsp;function foo(){&nbsp;&nbsp;&nbsp; &nbsp; for(var i = 0, len = list.length; i < len; i++){&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; var that = list[i];&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; list[i].onclick = (function(k){&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var info = that.innerHTML;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return function(){&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(k + "----" + info);&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; })(i);&nbsp;&nbsp;&nbsp; &nbsp; }&nbsp;&nbsp;}&nbsp;&nbsp;foo();&nbsp;&nbsp;方式2.事件代理var ul = document.querySelector('ul');&nbsp;&nbsp;var list = document.querySelectorAll('ul li');&nbsp;&nbsp;&nbsp;&nbsp;ul.addEventListener('click', function(ev){&nbsp;&nbsp;&nbsp; &nbsp; var ev = ev || window.event;&nbsp;&nbsp;&nbsp; &nbsp; var target = ev.target || ev.srcElemnt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; for(var i = 0, len = list.length; i < len; i++){&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if(list[i] == target){&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(i + "----" + target.innerHTML);&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; }&nbsp;&nbsp;});&nbsp;&nbsp;方式3. 引入jQuery,使用其中的on或delegate进行事件绑定(它们都有事件代理的特性)// delegate方法$("ul").delegate("li", "click", function(){&nbsp;&nbsp;&nbsp; &nbsp; var index = $(this).index();&nbsp;&nbsp;&nbsp; &nbsp; var info = $(this).html();&nbsp;&nbsp;&nbsp; &nbsp; alert(index + "----" + info);&nbsp;&nbsp;});&nbsp;&nbsp;&nbsp;// on方法$("ul").on("click", "li", function(){&nbsp;&nbsp;&nbsp; &nbsp; var index = $(this).index();&nbsp;&nbsp;&nbsp; &nbsp; var info = $(this).html();&nbsp;&nbsp;&nbsp; &nbsp; alert(index + "----" + info);&nbsp;&nbsp;});&nbsp;&nbsp;方式4. 使用ES6中的新特性let来声明变量用let来声明的变量将具有块级作用域,很明显可以达到要求,不过需要注意的是得加个'use strict'(使用严格模式)才会生效。var ul = document.getElementsByTagName("ul")[0];&nbsp;&nbsp;var list = ul.getElementsByTagName("li");&nbsp;&nbsp;&nbsp;&nbsp;function foo(){'use strict'&nbsp;&nbsp;&nbsp; &nbsp; for(let i = 0, len = list.length; i < len; i++){&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; list[i].onclick = function(){&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(i + "----" + this.innerHTML);&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; }&nbsp;&nbsp;}&nbsp;&nbsp;foo();&nbsp;&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript