**编辑此帖子是因为我发现问题确实在于无法绑定到ajax:success函数。jQuery绑定ajax:成功不适用于新创建的(ajax)项目的rails 3应用程序
***使用Rails 3.2.3
感谢您百忙之中阅读并设法帮助的时候。
我出的AJAX添加一个简单的淡入淡出功能:一个项目的成功被删除,具体如下:
$(document).ready(jQuery(function($) {
$('.delete').bind('ajax:success', function() {
$(this).closest('div').fadeOut();
});
}));
#For some reason had to pass the $ into the function to get it to work,
#not sure why this is necessary but doesn't work unless that is done.
在此之后,我想创建一个不显眼的jQuery对象时,用户添加的东西,并且在这些上也有工作删除按钮。我创建了一个create.js.erb文件,在创建新项目后调用 - 创建工作正常,但删除按钮无法访问ajax:success事件。
它确实从数据库中删除了点击数据,但.fadeOut永远不会绑定到它,所以它不会消失。该create.js.erb如下:
#$("div").append(html) here, then call the function below to try and bind the ajax:success function
$('.delete').bind('ajax:complete', function() {
$(this).closest('div').fadeOut();
});
如果我改变了绑定到点击功能,它的工作原理,但这并不占失败的Ajax调用:
#$("div").append(html) here, then call the function below to try and bind the ajax:success function
$('.delete').bind('click', function() {
$(this).closest('div').fadeOut();
});
所以,必须先绑定ajax:创建项目后成功。你们有什么想法,为什么这可能会发生?我是否需要在rails中做一些特殊的事情才能让新呈现的项目识别ajax事件?任何方向将不胜感激!
P.S.对于删除方法的控制器下面的情况下,任何人可以在那里发现了一个问题:
def destroy
@user = User.find(params[:user_id])
@item = @user.item.find(params[:id])
@item.destroy
respond_to do |format|
format.html { redirect_to user_path(@user) }
format.json { head :no_content }
format.js { render :nothing => true }
end
end
这是一个Rails 3.0.x和3.1/3.2的应用程序? – ScottJShea 2012-07-10 05:46:43
Rails 3.2.3是我正在使用的版本。这是非常可能的,我只是写错了代码,但是,因为你问了哪个版本的rails,我不得不问,你知道在早期版本的rails或类似的东西中有这样的错误吗? – Anthony 2012-07-15 02:11:54
有时候人们会在同一个项目中激活jQuery和Prototype。 Rails 3.0.x更经常发生。现在我再看一遍,您可能想要将第二个bind('bind_delete_animation')移动到'document.ready'中,而不是从'document.ready'调用的函数中。我从来没有成功地接受过文档之外的束缚。 – ScottJShea 2012-07-15 03:31:35