**编辑这篇文章是因为我发现问题实际上在于 rails 无法绑定到 ajax:success 函数。
***使用导轨 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();
});
如果我将其更改为绑定到 click 函数,它可以工作,但这并不能说明 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 事件?任何方向将不胜感激!
PS删除方法的控制器如下,以防任何人在那里检测到问题:
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