**编辑这篇文章是因为我发现问题实际上在于rails无法绑定到ajax:success函数。
***使用导轨3.2.3
感谢您花时间阅读并尝试提供帮助。
我在 ajax:success 删除项目上添加一个简单的淡出功能,如下所示:
$(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:success 的绑定一定会出现问题。你们知道为什么会发生这种情况吗?我是否需要在 Rails 中做一些特殊的事情才能让新渲染的项目识别 ajax 事件?任何方向将不胜感激!
附:删除方法的控制器如下,以防任何人都能够检测到那里的问题:
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