简体   繁体   中英

Rails 4: select DOM element with dynamically generated id

In my Rails 4 app, I have the following DOM structure on one of my views:

<tr id="post_row_<%= post.id%>">
  [...] # Truncated for brivety
  <td class="cell_content_center post_approval_section">
    [...] # Truncated for brivety
  </td>
</tr>

I need to update the content of the td with JavaScript.

In order to select it, I tried:

$('tr#post_row_<%= j post.id %> > td.post_approval_section').html('<%= j render(partial: "calendars/post_approval") %>');

but this gives me an error:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

As you can see, the id of the parent tr is dynamically generated.

How can I select it with JavaScript?

使用双引号(“”)代替单引号(''),例如:

$("tr#post_row_<%= j post.id %> > td.post_approval_section")

使用双“和#{}表示法:

$("tr#post_row_#{post.id} td.post_approval_section")

This code snippet will find the tr with id="post_row_ <%= j post.id %> ". Then inside tr , it will find td with class="post_approval_section".

$("tr#post_row_<%= j post.id %>").find('td.post_approval_section');

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