functionbindClick() { var ul = document.getElementById("list"); ul.onclick=functionhello(event){ console.log(event.target.getAttribute("index")); } for(var i=0;i<ul.children.length;i++){ ul.children[i].setAttribute("index",i); } } bindClick();
可以通过array.map方法获取到index值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
functionbindClick2() { var ul = document.getElementById("list"); // Node.children is a read-only property that returns a live HTMLCollection of the child elements of Node // ul.children 获取的是HTMLCollection对象 // 这个东西和arguments一样属于类数组对象需要转为数组才能使用数据的map方法(es5) // 因为map方法可以获取数组的index var lis = Array.prototype.slice.call(ul.children); ul.onclick = functionhello(event) { lis.map(function(cur, index, array) { if (cur == event.target) { console.log(index); } }); }; } bindClick2();
至少使用两种方法写出每隔1秒输出0,1,2的函数(需包含es6的实现)
普通情况最简单,用setInterval函数即可.
1 2 3 4 5 6
var a=0; functionadd(){ console.log(a++); } var int = setInterval("add()",1000); // clearInterval(int);