<html>
  <head>
   
  </head>
   <script type="text/javascript"
src="http://code.jquery.com/jquery-1.8.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {

$("#add").click(function(){
$.addApp();

});




});

$(function(){
$(".pp").click(function(){
 alert(1);});
 });


$.addApp=function(){
$("#cc").append("<p class='pp'>nihao</p>");
};


</script>
  <body>
  
  <input type="button" id="add" >
     <div id="cc">
     <p class="pp">nihao</p>
     </div>
  </body>
</html>
这里我是想让那个button每次点击之后, 都自动加入一个<p class="pp">nihao</p>
同时让$(".pp").click(function(){
 alert(1);});
 });能够执行
但是我点击button的时候添加进去的所有的p标签文件, 点击之后都没有反应。
我查看网页源代码的时候, 那些p都是在的, 而且class是pp没错, 
只有第一个p标签, 也就是我已经放在body里面的那个点击之后会弹出1

解决方案 »

  1.   

    你只绑定了第一个,以后加的要在addApp里重新绑定。另外,$.addApp 是什么想法?你可能会无意中覆盖了框架的方法,直接var addApp=function...就好了。
      

  2.   

    $('<p class='pp'>nihao</p>').click(function(){
         alert(1);});
         }).appendTo('#cc');
      

  3.   


    $(".pp").click(function(){
         alert(1);});
         });改成$(".pp").live('click',function(){
         alert(1);});
         });
      

  4.   

    live(type, [data], fn)
    jQuery 给所有匹配的元素附加一个事件处理函数,即使这个元素是以后再添加进来的也有效。
    .live() 方法能对一个还没有添加进DOM的元素有效,是由于使用了事件委托:绑定在祖先元素上的事件处理函数可以对在后代上触发的事件作出回应。传递给 .live() 的事件处理函数不会绑定在元素上,而是把他作为一个特殊的事件处理函数,绑定在 DOM 树的根节点上。
      

  5.   

    $(".pp").live('click',function(){//lz遇到的就是live和bind的区别
         alert(1);});
         });
      

  6.   

    哎,帮你实现了,并优化了一下。<html>
      <head>
    <script src="http://code.jquery.com/jquery-1.8.1.js"></script>
    <script> /**初始化*/
        $(function(){
    $("#add").click(addApp);
    addApp();
    });
    /**
    * 为控件绑定点击事件。
    */
        function bindClickEvent(){
    $(".pp").unbind().click(function(){
    alert(1);
    });
    };
        function addApp(){
    $("#cc").append("<p class='pp'>nihao</p>");
    //重新绑定事件
    bindClickEvent();
        };
        </script>
      </head>
      <body>
      <input type="button" id="add" >
      <div id="cc"></div>
      </body>
    </html>
      

  7.   

    $(".pp").click(function(){
         alert(1);});
    改成如下就OK了
    $(".pp").live('click',function(){
         alert(1);});
      

  8.   

    动态添加元素比较多的话,建议使用delegate()绑定事件,灵活性和性能都优于bind()和live()
      

  9.   

    楼上好多都说了
    楼主要学会.live()的用法这个方法可以为追加到dom中的元素绑定事件。。
      

  10.   

    事件委托1.4以前可以用live,1.4之后可以用delegate,1.7之后用on,在1.9里live和delegate都被移除了,只能用on了,参考:http://blog.csdn.net/borishuai/article/details/8115277