简体   繁体   中英

Pass dynamically generated div id's from Rails to javascript/coffeescript

I have a list of items for which I would like to reveal a more detailed description per item under the name of the item at the click of a button or link. For example, a very simple implementation would be using .toggle(). In Rails I have this for the descriptions:

<% @products.each do |product| %>
    <%= div_for(product, :class => "descriptions") do %>
        <%= product.description %>
    <% end %>
    <input type="button" id="button_<%= product.id %>" value="Show/hide" />
<% end %>

I would have to catch the dynamically generated div id's at the javascript/coffeescript side:

jQuery ->
$('#button_?????').click ->
    $('#product_ ????').toggle()

However, I'm unable to get this to work.

On the other hand, I might be able to accomplish the same result using something like '.closets()', like this:

jQuery ->
$('#button').click ->
    $('#button').closest('.descriptions').toggle()

However, I can't get this to work either. It seems to be a fairly simple task, but I'm just too unexperienced in javascript to get this to work. How to catch these dynamically generated divs on the javascript side? Any help would be very much appreciated.

If only DIVs you care about in this case will have a class of "descriptions", you can use jQuery's live function . It would look like this:

$('.descriptions').live("click", function() { ... });

So whenever a new item with the descriptions class is formed, it will gain that jQuery code for its click event.

In order to capture the dynamically generated div 's from Rails, you would normally do the following:

var divs = document.querySelectorAll('.descriptions');

Keep in mind, though, that querySelectorAll is NOT live, therefore any changes to the DOM will not be reflected in the NodeList .

jQuery has a great solution for this, as @MrDanA had suggested. However, the click handler needs to be on the button and not the description. Also, live has been deprecated. It needs to be replaced with on .

$('.descriptions').each(function(){
  var $this = $(this);
  var button = $this.next(); // assuming that the button is the next sibling
  button.on('click', function(e) {
    $this.toggle();
    e.preventDefault(); // to prevent page from jumping to the top of the page
  });
});

This should give you a good baseline. Let me know exactly how you'd like it to behave.

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