简体   繁体   中英

Does “this” object work in js.erb on Rails 3

There are many row in my table, and each row contains an button. When the button clicked, It will send remote js to my method in the controller. And it supposed to remove the row which the button located in.

Thanks in advance.

= form_tag kill_running_task_remote_focus_path, :method => :get, remote: true do


  def kill_running_task
    # binding.pry
    # kill_task(params)
    respond_to do |format|
      # format.html # new.html.erb
      format.js
      # format.js { render :action => 'add_to_cart'}
    end

  end

And I put the following code in my kill_running_task.js.erb If I put alert , it works, because I can see the alert windows. But it can not remove the row in the table.

$(this).closest("tr").remove();

On the page, when you click the button, the form will be submitted. The event listener has done his job and returned. Context closed. You can no longer access this in that context.

In your server's response js, the new context is window .

To solve your problem, firstly you need to assign unique id to each row according to the task's id.

Then, in server response, assign this action to specific row like

$("#task_#{task_id}").closest("tr").remove()

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