首先要引入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>