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

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>

初学者使用onclick时,要注意几点:

1、onclick属性的正确写法是οnclick="函数名()",它是带括号的,而不是οnclick="函数名"

2、如果onclick属性没有传入this对象,则在函数定义中不能使用$(this),否则解释器会因为找不到该对象而停止运行。

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值