[英]Rails 3, link_to with remote option - JavaScript is only working for the first click
I have a gallery of elements, each with a class of "#thumbnail", each thumbnail has a "delete" link below it. 我有一个图库图库,每个元素都有一个“ #thumbnail”类,每个缩略图下面都有一个“ delete”链接。
The problem with the code below is that the JavaScript "ajax:success" code only runs upon the first click ie it invokes the alert dialog, each time I subsequently click on another "delete" link the ajax fires & the action in my controller does what I expect, however the alert dialog is never shown again - unless I refresh the entire page & then of course it only works the first time again. 以下代码的问题在于,JavaScript“ ajax:success”代码仅在第一次单击时运行,即,它会调用警报对话框,每次我随后单击另一个“删除”链接时,ajax都会触发并且控制器中的操作会执行我所期望的,但是警告对话框永远不会再次显示-除非我刷新整个页面,然后当然它只会在第一次时起作用。
Can anyone see what is going wrong? 谁能看到出什么问题了? I have searched for an answer here but to be honest am a little lost.
我在这里寻找答案,但老实说有点迷路。
link_to (view): link_to(查看):
<%= link_to("Delete", "/graphics/0?url=#{image_url}", :method => "delete", :remote => true, :id => "delete-graphic") %>
Controller action: 控制器动作:
def destroy
render :json => {"result" => "ok"}
end
JS: JS:
$(document).ready(function() {
$('#delete-graphic').bind('ajax:success', function() {
alert("delete");
});
});
DOM IDs are intended to be unique. DOM ID是唯一的。 You should bind to a class rather than an ID, this will enable your jQuery method to work on every call rather than just on the first one.
您应该绑定到一个类而不是一个ID,这将使您的jQuery方法可以在每个调用上工作,而不仅仅是在第一个调用上工作。
Change your link_to
call to use a class: 更改您的
link_to
调用以使用一个类:
<%= link_to("Delete", "/graphics/0?url=#{image_url}", :method => "delete", :remote => true, :class => "delete-graphic") %>
Change your jQuery to bind to the class: 更改您的jQuery以绑定到该类:
$(document).ready(function() {
$('.delete-graphic').bind('ajax:success', function() {
alert("delete");
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.