Jquery给动态添加的元素添加事件

首先要引入jQuery库

利用jq的事件委托on(建议)

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
	<div class="input">
    <input class="whichkey" value="type something">
</div>
<button class="click">点击添加输入框</button>
<div id="log"></div>
<script>
	$('.input').on('keydown','.whichkey',function(e){
		//检测输入框按下的是那个键并显示键值
	   $('#log').html(e.type + ': ' +  e.which );  
	});
   $('.click').click(function(){
   		//动态添加输入框
      $('.input').append('<input class="whichkey" value="type something">');
	})
 </script>
</body>
</html>

利用jq的事件委托delegate(已废弃) delegate() 方法为指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数。 使用 delegate() 方法的事件处理程序适用于当前或未来的元素(比如由脚本创建的新元素)。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
	<div class="input">
	<input class="whichkey" value="type something">
	</div>
	<button class="click">点击添加输入框</button>
	<div id="log"></div>
<script>
 $('.input').delegate('.whichkey','keydown',function(e){
 	$('#log').html(e.type + ': ' +  e.which );  });
	$('.click').click(function(){
	     $('.input').append('<input class="whichkey" value="type something">');
	 })
</script>
</body>
</html>

转载于:https://my.oschina.net/qqlet/blog/1204642

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值