使用通过Jquery创建的对象注册现有事件处理程序

时间:2013-06-05 21:32:03

标签: javascript jquery event-handling append

好的,所以我有几个基本相同的对象,除了显示在它们上面的文本。单击它们时,使用现有事件处理程序执行操作

<div id="container">
  <div class="myclass">...<p>foo</p>...</div>
  <div class="myclass">...<p>bar</p>...</div>
  <div class="myclass">...<p>foo</p>...</div>
  ...etc etc
<div>
<div id="button" class="button">button-to-do-something</div>


$('.myclass').on('click', function () {
  ('this').css("background-color","red");
  //Some other junk happens here, but the red background is easily observed
});

$('#button').on('click', function() {
  $('#container').append('<div class="myclass">...<p>bar</p>...</div>');
});

我已经设置了一个按钮,在容器div中插入myclass div的另一个实例,但是,当单击动态创建的对象时,它们什么都不做。除了内部文本(在这个例子中为foo或bar)之外,代码与我的浏览器“inspect element”一起观察时完全相同。事件处理程序适用于随页面加载的元素,但动态创建的对象没有任何反应。

我可以为动态插入的对象注册现有的事件处理程序,还是必须做一些完全不同的事情?

2 个答案:

答案 0 :(得分:3)

你需要delegate它是这样的:

$('#container').on('click','.myclass', function () {
  ('this').css("background-color","red");
  //Some other junk happens here, but the red background is easily observed
});

$(document).on('click','.myclass', function () {
  ('this').css("background-color","red");
  //Some other junk happens here, but the red background is easily observed
});

答案 1 :(得分:2)

委派活动

$(staticContainer).on('click', '.myClass' function () {

staticContainer是绑定事件时DOM中存在的任何容器。

您的案例中的

Closest staticContainer可能是'#container'

越接近元素越好