jquery动态添加的元素,on绑定click事件不作用

真真实痛苦了,之前测试的时候明明也是这样写的是可以的,后来就莫名其妙的不可以了,不可以了怎么办,盘他,至于原因就随风吧,找不到之前为什么可以。

解决:on方法中要找到原选择器(如例.info),再找到动态添加的选择器(如列.delete)。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head>
<meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" >
<title>测试</title>
<script type= "text/javascript"
src= "../resources/js/jquery-1.11.1.min.js" ></script>
<script type= "text/javascript" >
$( function (){
//动态添加
$( ".add" ).on( "click" , function (){
console.log( "进来了" );
$( ".info" ).append( '<div class="delete"><h3>单击我来删除我</h3></div>' );
});
  //对动态添加的元素添加事件-删除
$( ".info" ).on( "click" , ".delete" , function (){
console.log( "进来了Delete!" );
$( this ).remove();
});
  });
</script>
  </head>
<body>
  <h2 class= 'add' >单击我添加动态元素</h2>
  <div class= "info" ></div>
  </body>
</html>
 

猜你喜欢

转载自www.cnblogs.com/love-dream-88/p/11433704.html
今日推荐