Ajax如何访问迭代生成的DOM元素的id?

时间:2017-01-03 09:45:25

标签: ruby-on-rails ajax iteration

我有一个Book模型和一个显示我的图书馆中的图书列表的页面。 要显示我在@books = Book.all上迭代的所有图书,请在表格中列出结果,并为用户提供预订或退回图书的机会。

<% @books.each_with_index do |book, index| %>
  <tr id="book-<%= book.isbn %>">
    <td class="title"> <%= book.title %> </td>
    <td class="author"> <%= book.author %> </td>
    <td>
      <div id="booking_form_<%= index + 1 %>">
        <% if current_user.booked?(book) %>
          <%= render 'book_selections/return_book' %>
        <% else %>
          <%= render 'book_selections/book_book' %>
        <% end %>
      </div>
    </td>
  </tr>
<% end %>

对于每本书,预订表格的唯一id由迭代的index生成。
我想使用Ajax为用户提供允许我的网页异步发送请求到服务器而不离开页面的机会。 因此,用户将看到提交表单的结果,而无需用户刷新应用程序的页面以重定向回页面。
问题是我无法访问表单id,因为迭代的index变量无法在js.erb文件中使用。 以下代码不起作用:

app/views/book_selections/create.js.erb

$("#booking_form_<%= index + 1 %>").html("<%= escape_javascript(render('book_selections/return_book')) %>");
$("#books_count").html('<%= current_user.books.count %>');

我正在寻找一种方法来保存索引变量并使其在js.erb文件中可用。

1 个答案:

答案 0 :(得分:1)

最好使用Book id代替迭代的index

<% @books.each do |book| %>
  <tr id="book-<%= book.isbn %>">
    <td class="title"> <%= book.title %> </td>
    <td class="author"> <%= book.author %> </td>
    <td>
      <div id="booking_form_<%= book.id %>">
        <% if current_user.booked?(book) %>
          <%= render 'book_selections/return_book' %>
        <% else %>
          <%= render 'book_selections/book_book' %>
        <% end %>
      </div>
    </td>
  </tr>
<% end %>

在您的AJAX调用中,将boook.id作为参数传递。

你可以做下面的事情:

# @book is the instance variable you would define in your controller action
# example: @book = Book.find_by_id(params[:id]) 
# params[:id] is the book id you would have sent as an argument
$("#booking_form_<%= @book.id %>").html("<%= escape_javascript(render('book_selections/return_book')) %>");