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

查看:32
本文介绍了使用 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天全站免登陆