本文介绍了Rails UJS“on”用于处理ajax事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Rails应用程序中使用jQuery方法on将事件附加到并不总是存在的表单上。当#myForm附加到文档时,似乎没有附加事件处理程序。

I'm using the jQuery method "on" in a Rails app to attach an event on a form which doesn't always exist. It doesn't seem to be attaching an event handler when #myForm is appended to the document.

这是UJS建议的用法()

$("#myForm").on("ajax:complete", function(xhr, status) { ... }

以下是我通常如何实现jQuery的 on(),但这似乎不起作用:

Here is how I usually implement jQuery's on(), but this does not seem to work:

$("body").on("ajax:complete", "#myForm", function(xhr, status) {...}

Rails UJS wiki:

Rails UJS wiki: https://github.com/rails/jquery-ujs/wiki/ajax

推荐答案

UJS与没有多大关系on function。这是由jQuery提供的,它需要多种形式.UJS只需触发 ajax:complete 事件,这样你就可以自己挂钩了。

UJS doesn't really have much to do with the on function. That's provided by jQuery, and it takes multiple forms. UJS simply fires the ajax:complete event so you can hook into it yourself.

选择器参数是可选的,所以

$(...).on("ajax:complete", function(xhr, status) { ... }

$(...).on("ajax:complete", "form", function(xhr, status) { ... }

是有效用途,但它们的工作方式有所不同。

are valid uses, though they work somewhat differently.

这篇关于Rails UJS“on”用于处理ajax事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 01:05