原生js addeventlistener可以给未来创建的元素添加事件 但是JQ要通过事件委托
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>添加</button>
<ul>
<li>我是原来的1</li>
<li>我是原来的2</li>
</ul>
<script type="text/javascript">
var ul = document.querySelector('ul');
var btn = document.querySelector('button');
btn.addEventListener('click', function(e) {
var nli = document.createElement('li');
nli.innerHTML = '我是新的li!!!' + '<a href="#">删除</a>'
ul.appendChild(nli);
})
var as = document.querySelector('a');
ul.addEventListener('click', function(e) {
console.log(111 + e.target.innerText);
})
</script>
</body>
</html>
JQ这边
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="jQuery.js"></script>
</head>
<body>
<button>哈哈哈哈</button>
<ul>
<li>asdasda</li>
<li>asdasdad</li>
</ul>
<script>
// $('li').click(function() {
// })
$('ul').on('click', 'li', function() {
console.log(this);
})
$('button').click(function() {
var li = $('<li>后来的LI</li>');
$('ul').append(li)
})
</script>
</body>
</html>