简体   繁体   English

新增元素$ .each和events

[英]Newly added elements $.each and events

I've read many posts already on the $.each and newly added elements + event attachment . 我已经读过许多关于$ .each和新添加的元素+事件附件的帖子。 Many of the current Questions regarding this topic on StackOverflow don't seem to work for me. 当前关于StackOverflow上该主题的许多问题似乎对我来说都不起作用。 $.on() is normally recommended since it allows us to append new elements and still maintain a single event listener + handler . 通常建议$ .on(),因为它允许我们添加新元素,并且仍然维护单个事件侦听器+处理程序

In my current code: 在我当前的代码中:

1. $('input[type="checkbox"]').on(“change”, function(e){}); 1. $('input[type="checkbox"]').on(“change”, function(e){});

  1. //I do a logical if-statement, if(this.checked) else //我做一个逻辑的if语句, if(this.checked) else

  2. //With-in the if -statement I run $.each , however, once I have appended new element in this context a new li to the ul , it stops working. //:在的if语句来我跑$.each但是,一旦我在这方面新追加新的元素liul ,它停止工作。

Out of the curiosity has anyone encountered something like this before, and if YES, how have you folks solved this? 出于好奇,以前没有人遇到过类似的事情,如果是,您是如何解决此问题的?

Some StackOverflow posts I have already seen: 我已经看过一些StackOverflow帖子:

jQuery $(element).each function doesn't work on newly added elements jQuery $(element).each函数不适用于新添加的元素

jquery: dynamically appending li items to ul then adding click, but click runs through each li jQuery:将li项目动态附加到ul,然后添加click,但是click贯穿每个li

Event binding on dynamically created elements? 在动态创建的元素上进行事件绑定?

Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call. 当前,您所使用的被称为“直接”绑定,它将仅附加到您的代码进行事件绑定调用时页面上存在的元素。

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. 委派事件的优势在于,它们可以处理来自后代元素的事件,这些事件在以后的时间添加到文档中。

As you are creating elements. 在创建元素时。

You need to use Event Delegation . 您需要使用事件委托 You have to use .on() using delegated-events approach. 您必须使用.on()使用委托事件方法。

General Syntax 一般语法

$(document).on(event, selector, eventHandler);

Ideally you should replace document with closest static container. 理想情况下,应使用最近的静态容器替换document

Example

$(document).on('change', 'input[type="checkbox"]', function(){
  //Your code
});

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

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