Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用通过Jquery创建的对象注册现有事件处理程序_Javascript_Jquery_Event Handling_Append - Fatal编程技术网

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

Javascript 使用通过Jquery创建的对象注册现有事件处理程序,javascript,jquery,event-handling,append,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

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

<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之外,当使用mybrowsers-inspect元素观察时,代码是完全相同的。事件处理程序适用于随页面加载的元素,但对动态创建的对象不起任何作用

我是否可以为动态插入的对象注册现有的事件处理程序,或者我是否必须执行完全不同的操作?

您需要这样委托它:

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

您需要这样授权:

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

委派活动

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

在您的情况下,最接近的staticContainer可能是“container”

它离元素越近,委派事件就越好

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

在您的情况下,最接近的staticContainer可能是“container”


越靠近元素,越好的

BTW考虑一个模板,例如把手。在JavaScript代码中硬编码的HTML代码不是一个好方法。BTW考虑一个模板,例如把手。在JavaScript代码中硬编码的HTML代码不是一个好方法。+1用于使用staticContainer而不是document。向您保证OP会询问为什么staticContainer未定义。不,我知道如果我使用它为什么会未定义。谢谢你的回答=+1用于使用staticContainer而不是文档。向您保证OP会询问为什么staticContainer未定义。不,我知道如果我使用它为什么会未定义。谢谢你的回答=谢谢你的帮助=谢谢你的帮助=
$(staticContainer).on('click', '.myClass' function () {