简体   繁体   English

jQuery不适用于文档加载后创建的元素

[英]jQuery doesn't work with elements created after document load

I created two elements dinamically with jQuery: 我用jQuery创建了两个元素:

a picture and a Close button 图片和关闭按钮

I wrote the code to remove both in doument.ready function: 我写了代码来删除doument.ready函数:

$( ".deletepreview" ).click(function() {
    code = $(this).data("prevcode");
    $('#'+code).remove();
    $(this).remove();
});

But it doesn't work, and I think this is because the code doesn't search in the code created after the document load. 但它不起作用,我认为这是因为代码不会搜索文档加载后创建的代码。

How can I solve this problem? 我怎么解决这个问题?

You need to use delegated events via on() if you want events to be handled on dynamically added elements: 如果要在动态添加的元素上处理事件,则需要通过on()使用委托事件:

$(document).on("click", ".deletepreview",function() {
  var code = $(this).data("prevcode");
  $('#'+code).remove();
  $(this).remove();
});

I slightly modified your example: always declare variables with var in closures except when you need to. 我略微修改了你的例子:除非你需要,总是用闭包中的var声明变量。

For dynamically created elements try using delegation with on like: 对于动态创建的元素,尝试使用委托与on

Event handlers are bound only to the currently selected elements; 事件处理程序仅绑定到当前选定的元素; they must exist on the page at the time your code makes the call to .on(). 它们必须存在于您的代码调用.on()时的页面上。 To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. 要确保元素存在且可以选择,请在文档就绪处理程序内对页面上HTML标记中的元素执行事件绑定。 If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. 如果将新HTML注入页面,请在将新HTML放入页面后选择元素并附加事件处理程序。 Or, use delegated events to attach an event handler, as described next. 或者,使用委托事件来附加事件处理程序,如下所述。

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. 委托事件的优点是,它们可以处理来自稍后添加到文档的后代元素的事件。 By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. 通过选择在附加委托事件处理程序时保证存在的元素,您可以使用委派事件来避免频繁附加和删除事件处理程序的需要。 This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. 例如,此元素可以是模型 - 视图 - 控制器设计中视图的容器元素,如果事件处理程序想要监视文档中的所有冒泡事件,则可以是文档。 The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready. 在加载任何其他HTML之前,文档元素在文档的头部可用,因此可以安全地将事件附加到那里而无需等待文档准备就绪。

Code: 码:

$('body').on('click', '.deletepreview', function() {
  var code = $(this).data('prevcode');
  $('#'+code).remove();
  $(this).remove();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM