动态生成ul的li并添加addEventListener

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>li</title> 
<style>
	ul{
		list-style:none
	}
	li{
		width:200px;
		height:30px;
		background: green;
		border:1px solid #000;
		margin:5px auto;
	}
</style>
</head>
<body>
	<button onclick="addFunction()">点我增加</button>
	<ul></ul>
	<script type="text/javascript">
	var num = 1;
	var u=document.querySelector("ul");
	function addFunction(){
	  var l=document.createElement('li')
	  var t=document.createTextNode(num);
	  l.appendChild(t);
	  u.appendChild(l);
	  num++
	};
	u.addEventListener('click',function(e){
	  console.log(777);
	  if(e.target && e.target.nodeName.toUpperCase() === 'LI') {
		console.log(e.target.innerHTML);
	  }
	})
	</script>
</body>
</html>
发布了90 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/me_never/article/details/103842404
今日推荐