欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

jquery 动态生成的元素的事件无法绑定

shiping1 的头像

今天遇到一个问题,由Jquery动态去生成一段html元素后,这些新生成的元素绑定的事件不起作用,后来查阅解决,废话不说,上代码,以下代码目的是点击button按钮,移除span区域。

Html代码  收藏代码
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  2. <html>  
  3.  <head>  
  4.   <title> New Document </title>  
  5.   <meta name="Generator" content="EditPlus">  
  6.   <meta name="Author" content="">  
  7.   <meta name="Keywords" content="">  
  8.   <meta name="Description" content="">  
  9.   <script type="text/javascript" src='http://code.jquery.com/jquery-1.9.1.js'></script>  
  10.     
  11.  </head>  
  12.   
  13.  <body>  
  14.  <input type='button' id='creates' value='test'>  
  15.  <div id='aDiv'>  
  16.  <span>  
  17.   <li><input type='button' name='a' value='1'></li>  
  18.   <li>xxx</li>  
  19.  </span>  
  20.  <span>  
  21.   <li><input type='button' name='a' value='2'></li>  
  22.   <li>xxx</li>  
  23.  </span>  
  24.  </div>  
  25.  <script type="text/javascript">  
  26.     $(function(){  
  27.         /*$('input[name=a]').each(function(){  
  28.             $(this).click(function(){  
  29.                 $(this).parent().parent().remove();  
  30.             });  
  31.         });*/  
  32.         $('input[name=a]').click(function(){  
  33.                 $(this).parent().parent().remove();  
  34.         });  
  35.         $('#creates').click(function(){  
  36.             $('#aDiv').append('<span><li><input type=button name=a value=1></li><li>xxx</li></span>');  
  37.         });  
  38.         //注释以下代码,动态生成的Html元素点击button时不能够被移除  
  39.         $('div').delegate('input[name=a]','click',function(){$(this).parent().parent().remove()});  
  40.           
  41.     })  
  42.   </script>  
  43.  </body>  
  44. </html>  

 

 

总结:

      1. click或者是...bind('click',function(){...});,click是bind('click',...)的简化形式,是JQuery扫描文档找出所有的$(‘input[name=a]’)元素,并把函数绑定到每个元素的click事件上,表明是现有页面上存在的元素,动态生成的元素不包括在内。

       2.delegate方法,代理或者说是委托,实现原理是事件的冒泡,在指定的祖先元素中注册事件(delegate在特定元素上),元素事件触发,传播到这个元素然后进行筛选。可以在祖先元素中绑定事件,比如上面的div是祖先元素,而新生成的元素都是div的子元素,所以动态生成的元素的事件就可以绑定了。

       delegate官网介绍:Attach a handler to one or more events for all elements that match the selector,now or in the future, based on a specific set of root elements.

来自 
http://zhangzhaoaaa.iteye.com/blog/1897665


普通分类: