今天遇到一个问题,由Jquery动态去生成一段html元素后,这些新生成的元素绑定的事件不起作用,后来查阅解决,废话不说,上代码,以下代码目的是点击button按钮,移除span区域。
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <title> New Document </title>
- <meta name="Generator" content="EditPlus">
- <meta name="Author" content="">
- <meta name="Keywords" content="">
- <meta name="Description" content="">
- <script type="text/javascript" src='http://code.jquery.com/jquery-1.9.1.js'></script>
- </head>
- <body>
- <input type='button' id='creates' value='test'>
- <div id='aDiv'>
- <span>
- <li><input type='button' name='a' value='1'></li>
- <li>xxx</li>
- </span>
- <span>
- <li><input type='button' name='a' value='2'></li>
- <li>xxx</li>
- </span>
- </div>
- <script type="text/javascript">
- $(function(){
- /*$('input[name=a]').each(function(){
- $(this).click(function(){
- $(this).parent().parent().remove();
- });
- });*/
- $('input[name=a]').click(function(){
- $(this).parent().parent().remove();
- });
- $('#creates').click(function(){
- $('#aDiv').append('<span><li><input type=button name=a value=1></li><li>xxx</li></span>');
- });
- //注释以下代码,动态生成的Html元素点击button时不能够被移除
- $('div').delegate('input[name=a]','click',function(){$(this).parent().parent().remove()});
- })
- </script>
- </body>
- </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