**编辑这篇文章是因为我发现问题确实出在 rails 无法绑定(bind)到 ajax:success 函数上。
***使用 rails 3.2.3
感谢您花时间阅读并尝试提供帮助。
我在ajax:success of an item being deleted上添加了一个简单的fade out函数,如下:
$(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 从未绑定(bind)到它,因此它不会消失。 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();
});
如果我将其更改为绑定(bind)到点击功能,它会起作用,但这并不能解释失败的 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();
});
因此,在创建项目后,绑定(bind)到 ajax:success 一定有问题。你们知道为什么会这样吗?我是否需要在 Rails 中做一些特殊的事情来让新呈现的项目识别 ajax 事件?任何方向将不胜感激!
附言删除方法的 Controller 在下面,以防任何人都能在那里检测到问题:
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
最佳答案
问题听起来像是绑定(bind)发生在生成元素之前。试试这个:
$(document).on('ajax:success', '.delete', function(e) {
$(e.currentTarget).closest('div').fadeOut();
});
关于javascript - jQuery 绑定(bind) ajax :success not working in rails 3 app for newly created (ajax) items,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11406805/