您的位置:首页 > Web前端 > JQuery

jquery的on()方法和用event.target判断是那个子元素触发事件

2016-05-10 16:07 615 查看
jquery的事件处理语句一般是:

父元素.on('click', function(event) {

event.preventDefault();

if( $(event.target).is( 子元素) ) {

...........

}

});

on() 方法在被选元素及子元素上添加一个或多个事件处理程序。

自 jQuery 版本 1.7 起,on() 方法是 bind()、live() 和 delegate() 方法的新的替代品。该方法给 API 带来很多便利,我们推荐使用该方法,它简化了 jQuery 代码库。

<!DOCTYPE html>
<html>
<head>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("p").on("click",function(){
alert("The paragraph was clicked.");
});
});
</script>
</head>
<body>

<p>Click this paragraph.</p>

</body>
</html>
演示地址:http://www.runoob.com/try/try.php?filename=tryjquery_event_on

在外层绑定 click 事件,在事件监听器中检查下 event.target 是不是 a 元素。

出自https://segmentfault.com/q/1010000003046386

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
<title>无标题文档</title>
</head>
<script type="text/javascript">
$(function(){
$('p').on('click',function(event){

if($(event.target).is($('a')))
alert("The paragraph was clicked.");
});

}
);
</script>

<body>
<p>
<a href="#">登录</a>
</p>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: