示例代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="getMoreField">
<button id="getMoreBtn">更多1</button>
</div>
<script type="text/javascript" src="https://www.class4ever.com/_static/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(function(){
var $times;
$times=1;
//这是on方法
$('#getMoreField').on('click','button',function(){
$times++;
$('#getMoreField').html('<button id="getMoreBtn">更多'+$times+'</button>');
});
//而click方法只能用1次
/*
$('#getMoreBtn').click(function(){
$times++;
$('#getMoreField').html('<button id="getMoreBtn">更多'+$times+'</button>');
});
*/
});
</script>
</body>
</html>
上面代码中, 如果用注释中的click方法, 则只能有效一次.
而on方法绑定于父元素.
有人说:on方法可以给未来的元素绑定事件.