简体   繁体   English

使用JQuery ajax在DOM操作后附加事件

[英]Attaching events after DOM manipulation using JQuery ajax

How to attach all events after manipulating the dom using ajax response. 在使用ajax响应操纵dom之后如何附加所有事件。 I have a ajax request which get a html response which is basically a fragment of html. 我有一个ajax请求,它获取一个html响应,该响应基本上是html的一个片段。 that fragment HTML have many buttons. 该片段HTML有很多按钮。 I want to refresh the dom so previously declared and attached events be applied into that fragment too. 我想刷新dom,以便将先前声明和附加的事件也应用于该片段。 I dont want to keep on adding each events for each button using jquery on(). 我不想继续使用jquery on()为每个按钮添加每个事件。 how else to do it? 还有其他办法吗?

You can use delegated event handling which is set up ahead of time and can be made to apply to newly added DOM elements. 您可以使用预先设置的委托事件处理,并且可以将其应用于新添加的DOM元素。 Delegated event handling is done with .on() and generally takes the form of: 委托事件处理是使用.on() ,通常采用以下形式:

$("static parent selector").on('click', 'selector for dynamic element', fn);

There is no clean way to just run your event installing code again and have it only apply to newly added DOM elements. 没有干净的方法可以再次运行事件安装代码,并且仅将其应用于新添加的DOM元素。 You would have to put that code in a function and code it such that it never adds an event handler more than once and then you could call that function again after adding items to the DOM. 您将必须将该代码放入函数中并对其进行编码,以使它永远不会添加事件处理程序超过一次,然后在将项目添加到DOM之后可以再次调用该函数。 Or, you could make the function take an argument for a parent object and only add event handlers in the newly added DOM hierarchy. 或者,您可以使函数接受父对象的参数,而仅在新添加的DOM层次结构中添加事件处理程序。

Here's another relevant answer about delegated event handling: Does jQuery.on() work for elements that are added after the event handler is created? 这是有关委托事件处理的另一个相关答案: jQuery.on()是否可用于创建事件处理程序之后添加的元素?

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

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