2016-08-12 51 views
0

回调函数不适用于JQuery添加的元素。在我的示例中,有一个父分区class=parent。点击它后,<span class="child">Child</span>正在被添加。但是当我点击孩子时,它不会提示消息。请参考下面如何将回调函数添加到由JQuery添加的元素

<html> 
    <head> 
     <style> 
      .parent{ 
       width: 50px; 
       height: 30px; 
       line-height: 30px; 
       background-color: #232323; 
       color: #fff; 
       text-align: center; 
      } 

      .child{ 
       width: 50px; 
       height: 30px; 
       line-height: 30px; 
       background-color: #f3b556; 
       color: #232323; 
       text-align: center; 
       margin-top: 10px; 
      } 
     </style> 
    </head> 
    <body> 
     <div class="parent"> 
      <span>Parent</span> 
     </div> 


     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
     <script> 
      $('.parent').click(function(){ 
       alert('parent clicked'); 
       $(this).after("<span class='child'>child</span>"); 
      }); 
      $('.child').click(function(){ 
       alert('child clicked'); 
      }); 
     </script> 
    </body> 
</html> 
+0

您需要使用'.on'而不是.click。看看这个答案http://stackoverflow.com/a/1207393/1270865 – cafebabe1991

回答

0

使用活代表团例子,因为.child是动态的添加元素的正常事件监听器不会在将来产生孩子的注册click

$("body").on("click", ".child", function(){ 
    alert('child clicked'); 
}); 
+0

$(document).on(“click”,“。child”,function(){})也可以吗? – mayk

+0

是的,那也可以。但最好的方法是选择最接近的选择器,在这个例子中它将是'body'。 @mayk – eisbehr

+0

太棒了,很有用,非常感谢你 –

-1

作为DOM manuplation正在发生,并且它穿过至$('.child').click(function())功能,都没有发现在任何DOM相应的元件来操纵。当你动态地添加这个元素时,你必须在动态添加类之后绑定/注册事件,以注册要监听的事件。 您可以通过

$('.parent').click(function(){ 
       alert('parent clicked'); 
       $(this).after("<span class='child' onclick='ChildelementClick()'>child</span>"); 
      }); 
function ChildelementClick(){ 
// do somehing 
} 

做,或者您也可以使用@eisbehr

0

给出的例子会委派从父事件。

当你创建一个新的对象时,它缺少事件监听器,可以在其它元素与其相同的类之前添加事件监听器。

但是,如果添加监听到现有inmutable父,它将始终工作:

$("#existingContainer").on("click", ".child", function() { 
    //whatever 
}) 

这样,该事件被抓获#existingContainer,但是当它捕获时,才会执行回调在位于#existingContainer内部的“.child”对象中,无论这个.child对象是否在创建事件侦听器后添加。