使用JQuery ajax在DOM操作后附加事件 [英] Attaching events after DOM manipulation using JQuery ajax

查看:123
本文介绍了使用JQuery ajax在DOM操作后附加事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在使用ajax响应操作dom后附加所有事件。我有一个ajax请求,得到一个基本上是html的片段的html响应。该片段HTML具有许多按钮。我想刷新dom,以前声明和附加的事件也被应用到该片段中。我不想继续使用jquery on()添加每个按钮的每个事件。如何做呢?

How to attach all events after manipulating the dom using ajax response. I have a ajax request which get a html response which is basically a fragment of html. that fragment HTML have many buttons. I want to refresh the dom so previously declared and attached events be applied into that fragment too. I dont want to keep on adding each events for each button using jquery on(). how else to do it?

推荐答案

您可以使用提前设置的委托事件处理,并可以应用到新添加的DOM元素。委托事件处理是用 .on()完成的,通常采取以下形式:

You can use delegated event handling which is set up ahead of time and can be made to apply to newly added DOM elements. Delegated event handling is done with .on() and generally takes the form of:

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

没有干净的方法,只需再次运行您的事件安装代码,并且只适用于新添加DOM元素。您必须将该代码放在一个函数中并对其进行编码,以使其不会多次添加事件处理程序,然后可以在将项添加到DOM后再次调用该函数。或者,您可以使该函数为父对象提供参数,并在新添加的DOM层次结构中仅添加事件处理程序。

There is no clean way to just run your event installing code again and have it only apply to newly added DOM elements. 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. Or, you could make the function take an argument for a parent object and only add event handlers in the newly added DOM hierarchy.

这是另一个有关委托事件处理的相关答案: jQuery.on()是否适用于创建事件处理程序后添加的元素?

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 ajax在DOM操作后附加事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆