jquery从1.7版本添加了on,而从1.9+版本已经不再支持live,取而代之的是on事件。那么我们应该怎么写呢?现举例如下,GOODLUCK!
如果简单的将原来的live换成on,可能会使很多事件不起作用,如下面的实例中点击增加按钮后,在新添加的区域点击后没有反应。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>live V on</title>
</head>
<body>
<div class="add">
<div class="plus" style="width:200px;height:200px;background-color: yellowgreen">点增加后再点击增加的内容测试点击事件</div>
</div>
<button id="btn">增加</button>
<script type="text/javascript" src="https://www.dvy.com.cn/wp-content/themes/dux/js/libs/jquery-1.12.3.min.js?ver=1.4"></script>
<script>
$("#btn").click(function () {
$(".add").append($(".add:first").html());
});
$(".plus").on("click", function () {
alert("clicked");
});
</script>
</body>
</html>
我们将写法改写一下:
$(document).on("click",".plus", function () {
alert("clicked");
});
完整的HTML,你再试一下,是不是可以使用了?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>live V on</title>
</head>
<body>
<div class="add">
<div class="plus" style="width:200px;height:200px;background-color: yellowgreen">点增加后再点击增加的内容测试点击事件</div>
</div>
<button id="btn">增加</button>
<script type="text/javascript" src="https://www.dvy.com.cn/wp-content/themes/dux/js/libs/jquery-1.12.3.min.js?ver=1.4"></script>
<script>
$("#btn").click(function () {
$(".add").append($(".add:first").html());
});
$(document).on("click",".plus", function () {
alert("clicked");
});
</script>
</body>
</html>
达维营-前端网