Jquery事件不适用于动态追加的元素 [英] Jquery events do not work on dynamically appended elements

查看:106
本文介绍了Jquery事件不适用于动态追加的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将新DOM对象附加到某个Div并且它可以工作,但不知何故 - 我为这些新附加对象编写的事件没有响应。为什么会这样?

I'm trying to append new DOM objects to some Div and it works, but somehow - the events that I programmed for these new appended objects do not respond. Why is that?

我在这里附上一个简单的例子:点击段落应该隐藏的任何段落。然而,对于使用.append添加的段落,它不起作用。

I attach here a simple example: upon click on any paragraph the paragraph should hide. Yet, for paragraph that were added using .append, it doesn't work.

http://jsfiddle.net/xV3HN/

这是我的代码:

$(document).ready(function(){

$("#add").click(function(){
     $("#containerDiv").append("<p> I should hide as well if you click me </p>");
  });

 $("p").click(function(){
     $(this).hide();
  });

});


推荐答案

您需要使用。在上处理动态元素的事件。

试试这个:

You need to use .on to handle events of dynamic elements.
try this:

  $(document).on('click', 'p', function(){
     $(this).hide();
  });

DEMO

这篇关于Jquery事件不适用于动态追加的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆