开发者

How to make ids of HTML elements unique so that something could be appended in the correct element on ajax response

Jquery is being used on rails views. Here a code sample:

<div id="comments" class="comments">
  <%= render :partial =>开发者_如何学编程; 'comment', :collection => @comments %>
</div>

<script type="text/javascript">
$(function() {
  $('#new_comment').bind('ajax:success', function(event, data, status, xhr) {
     $('#comments').append('<div class="comment-item">' + data.text + '</div>');
  });
});  
</script>

I have a form that sends an ajax request and on response the javascript function is called. I have multiple places in the page with this pattern and its dynamic. I need to make the id of div unique on append the response in correct id. How do I do that?


In Rails you can use content_tag_for or div_for helpers to get a class

<%= div_for @post do %>
  <!-- stuff -->
<% end %>

Which is the same as:

<%= content_tag_for :div, @post do %>
  <!-- stuff -->
<% end %>

Will result in something like:

<div class="posts" id="post_42">
  <!-- stuff -->
</div>

In HAML, you can use the square brackets to achieve the same:

%div[@post]
  / stuff
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜