Rails 4: select DOM element with dynamically generated id

点点圈 提交于 2020-01-17 02:21:24

问题


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


来源:https://stackoverflow.com/questions/33820080/rails-4-select-dom-element-with-dynamically-generated-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!