Rails 4: select DOM element with dynamically gener

2019-08-31 00:53发布

问题:

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?

回答1:

Use double quotation(" ") instead of single quotes(' ') like:-

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


回答2:

Use double " and #{} notation:

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


回答3:

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');