简体   繁体   English

Ajax成功事件未触发动态添加的链接

[英]ajax success event not triggering for dynamically added links

In my rails 4 app I am having trouble getting ajax "success" event triggering for links that are added to a page dynamically with jquery. 在我的Rails 4应用程序中,我无法获取ajax“成功”事件触发来触发使用jquery动态添加到页面的链接。 I am creating markup like the following and dynamically adding it to a page. 我正在创建如下标记,并将其动态添加到页面中。

<a data-confirm="Are you sure?" data-method="delete" data-remote="true" href="/mylink" rel="nofollow">delete</a>

The following DOES trigger: 以下DOES触发:

$(document).on("ajax:success"

But the version that does NOT trigger and the one I want to use is: 但是不会触发的版本和我要使用的版本是:

$("a[data-remote]").on("ajax:success"

Any idea why the $(document) version works while the $("a[data-remote]") version does not? 知道为什么$(document)版本有效而$("a[data-remote]")版本无效吗? To clarify, it does not work specifically when things are added dynamically. 要澄清的是,当动态添加事物时,它并不专门起作用。 For links that are already on the page they trigger the events just fine. 对于页面上已经存在的链接,它们可以触发事件。

Note: Turbolinks is removed. 注意:Turbolinks被删除。

Thats because the .on() event handler doesn't handle the dynamically added elements unless you specify it like this: 那是因为.on()事件处理程序不会处理动态添加的元素,除非您这样指定:

$(document).on('ajax:success', 'a[data-remote]', function(){});". 

It works with "$(document)" because the event handler captures the event when it bubbles up to it's parent element, in this case 'document'. 它与“ $(document)”一起使用,因为事件处理程序会在事件上升到其父元素(在本例中为“ document”)时捕获事件。

You should add the event handler to the parent element that contains all 'a[data-confirm]' so it doesn't filter each event, or you could specify like the code above. 您应该将事件处理程序添加到包含所有'a [data-confirm]'的父元素中,这样它就不会过滤每个事件,或者您可以像上面的代码一样进行指定。

Here's more on event bubbling and capturing . 这是有关事件冒泡和捕获的更多信息

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

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