事件委托 面试题
2018-05-05 本文已影响0人
jh2k15
给ul下面的li加上点击事件,点击哪个li,就显示那个li的innerHTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<ul id="ul">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
</ul>
</body>
</html>
let ul=document.getElementById('ul'),
lis=ul.getElementsByTagName('li')
let len=lis.length
for(let i=0;i<len;i+=1){
lis[i].addEventListener('click',function(){
alert(lis[i].innerHTML)
})
}
委托给li上层的ul
let ul=document.getElementById('ul')
ul.addEventListener('click',function(e){
alert(e.target.innerHTML)
})
兼容性
let ul=document.getElementById('ul');
ul.addEventListener('click',function(e){
e=e || window.e;
let target=e.target || e.srcElement;
if(target.tagName.toLowerCase() === 'li'){
alert(target.innerHTML)
}
})
let ul=document.getElementById('ul');
ul.addEventListener('click',function(e){
console.log(e)
})