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

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

问题描述

如何使用Ajax响应操纵DOM后附加的所有事件。我有得到一个HTML响应这基本上是HTML的一个片段一个Ajax请求。该片段HTML有许多按钮。我想刷新DOM所以previously声明和连接事件被应用到该片段了。我不想继续使用的jQuery上的每个按钮添加的每个事件()。要不然怎么办呢?

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元素委派的事件处理。委托事件处理完成与。对(),通常采用以下格式:

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);

有没有干净的方式只是运行您的活动C再次安装$ C $,并将它仅适用于新添加的DOM元素。你将不得不把那个code在功能和code以使其永远不会添加一个事件处理程序超过一次,然后你可以将项目添加到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.

下面是关于委派的事件处理另一个相关答案:<一href="http://stackoverflow.com/questions/9814298/does-jquery-on-work-for-elements-that-are-added-after-the-event-handler-is-cre/9814409#9814409">Does 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天全站免登陆