话不多说
var oul = document.getElementsByClassName('oul')[0]
var liArr = document.getElementsByTagName('li')
var str = ''
for (var i = 1; i <= 10; i++) {
str += '
'+i+''}
oul.innerHTML = str
for (var i = 0; i < liArr.length; i++) {
liArr[i].index = i+1
liArr[i].onclick = function() {
console.log('您点击了第'+this.index+'个li');
}
}
这样写有个问题,就是当li有100000个甚至更多的时候,就会有较长的等待时间,怎么解决呢? 那就是事件委托了!怎么做呢
var oul = document.getElementsByClassName('oul')[0]
var liArr = document.getElementsByTagName('li')
var str = ''
for (var i = 1; i <= 10; i++) {
str += '
'+i+''}
oul.innerHTML = str
oul.οnclick=function(ev) {
var ev = ev || window.event
var target = ev.target || ev.srcElement
if (target.nodeName.toLowerCase() == 'li'){
var index;
for (var i = 0; i < liArr.length; i++) {
if (target == liArr[i]){
index = i+1
console.log('您点击了第'+index+'个li');
}
}
}
}