日期:2014-05-16  浏览次数:20360 次

一个jquery的问题, 怎么都解决不了
<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

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

引用:
JavaScript code
?



1234

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


JavaScript code
?



1234

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

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

------解决方案--------------------
哎,帮你实现了,并优化了一下。





<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>





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