简体   繁体   中英

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.

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.

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("Delete", "/graphics/0?url=#{image_url}", :method => "delete", :remote => true, :id => "delete-graphic") %>

Controller action:

  def destroy
    render :json => {"result" => "ok"}
  end

JS:

  $(document).ready(function() { 
    $('#delete-graphic').bind('ajax:success', function() {
      alert("delete");
    });
  });

DOM IDs are intended to be unique. 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.

Change your link_to call to use a class:

<%= link_to("Delete", "/graphics/0?url=#{image_url}", :method => "delete", :remote => true, :class => "delete-graphic") %>

Change your jQuery to bind to the class:

$(document).ready(function() { 
  $('.delete-graphic').bind('ajax:success', function() {
    alert("delete");
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM