動態生成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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章