简体   繁体   中英

Rails and coffeescript popup only working on first object in array

I have a products page listing several different products. When a products main image is clicked i would like a popup/lightbox to display with another image of that product and additional information.

However, the click event is only working for the first product:

$(document).ready ->
 i = $(".main-image").attr("data-productid")
 button = $("#single_" + i)
 button.on "click", ->
  $("#product_popup").show()

The html/erb:

<% products.each do |product| %>
<% if product.on_display? %>
  <div class="grid_1">
  <li id="product_<%= product.id %>" class="columns product three <%= cycle("alpha", "secondary", "", "omega secondary", :name => "classes") %>" data-hook="products_list_item" itemscope itemtype="http://schema.org/Product">
    <div class="main-image" id="single_<%= product.id %>" data-productid="<%= product.id %>">
      <%= large_image(product, :itemprop => "image", :class => "product-image", :id => product.id) %>
    </div><!-- main-image-->
    <%# ******LIGHTBOX******* %>
    <div id="product_popup">
        <%= large_image(product, :itemprop => "image", :class => "product-image") %>
    </div><!-- product_popup -->

Thanks for any help. I appreciate it.

Try this

jQuery ->
  $(".main-image").each () ->
    i = $(this).attr("data-productid")
    $("#single_" + i).on "click", ->
      $("#product_popup").show()

You need to call each on you .main-image selector, so the code inside each is executed to each of your div.main-image. notice the $(this) inside the each, that will be relative to each of your div during each iteration of the each loop.

I thing you can refactor like this (try the solution above first to confirm it's working)

jQuery ->
  $("div.main-image").on "click", ->
    $("div#product_popup").show()

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