jquery在1.7以后使用放弃了使用bind方法为元素绑定方法,使用on()绑定方法。我们这里就单单讲解on()绑定方法的使用方式。
1、指定元素绑定方法
该方法利用jquery提供的选择器方法匹配到指定的元素并为其绑定元素。
语法:$(selector).on(type,fun);
语法如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>on方法</title>
<script src="../jquery-1.7.2.min.js"></script>
</head>
<body>
<div id="div1">
<p>在p元素中</p>
</div>
<div id="div2">
<cite>47328947398578439759</cite>
<p>在p元素中</p>
</div>
</body>
<script>
$(function(){
$("p").on("click",function(){
alert("nihao");
});
});
</script>
</html>
上面的代码中为文档中的<p>元素绑定点击事件。凡是点击文档中的p元素浏览器都会弹出系统消息。
2、指明区域为区域中的指定元素绑定时间
语法:$(selector).on(type,'selectorB',fun);
$(selector)的作用是为了匹配到指定元素对象A。
selectorB为待绑定的元素,它为A元素对象的后代元素。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>on方法</title>
<script src="../jquery-1.7.2.min.js"></script>
</head>
<body>
<div id="div1">
<p>在p元素中</p>
</div>
<div id="div2">
<cite>47328947398578439759</cite>
<p>在p元素中</p>
</div>
</body>
<script>
$(function(){
//为id="div2"的后代元素p指定点击事件
$("#div2").on("click","p",function(){
alert("nihao");
});
});
</script>
</html>