0

我正在加载一组@products,这些@products 具有我动态计算的不断变化的属性。我不想对初始页面索引上的所有@products 执行所有计算。相反,我只想在将鼠标悬停在图像上时执行和显示计算。

我首先创建 jQuery 调用来显示一个弹出框,以包含 products/index.html.erb 中每个产品的计算,如下所示:

产品/index.html.erb

<script type="text/javascript">
  jQuery(function($){
    <% @products.each do |product| %>
      $('#calc_<%= product.id %>').hover(function() {
        $('#pid_<%= product.id %>').show() 
      }, function() {
        $('#pid_<%= product.id %>').hide()
      });
   <% end %>
});
</script>

<table class='list'>
  <%= render :partial => "products/product", :collection => @products %>
</table>

我的 _product.html.erb:

<%= image_tag('/images/info.png', :id => "calc_#{product.id}") %>
<div class='pid_display' id='pid_<%=product.id %>'></div>    

我的CSS:

.pid_display {
    height: 80px; 
    width: 200px; 
    background-color: #eee; 
    display: none; 
    padding-top: 8px;
    position: absolute;
}

我正在尝试像这样调用对 product.id 执行计算的页面(尽管我不知道这是否正确):

 jQuery.ajax("products/calculations/<%= product.id %>");

当我尝试组合对计算页面的调用以便在弹出框中显示结果时,两者都会触发。换句话说,会出现一个弹出框,并且日志显示计算是从 products_controller 执行的。

如何结合这两个调用在弹出框中显示计算结果?

4

2 回答 2

0

您可以使用attr_accessible来确定模型对于 @products 的第一个元素具有哪些属性,并将其保存在数组中。

然后,您可以使用这些属性使用 product.method("attribute") 从对象中获取值

于 2013-02-23T09:21:15.410 回答
0

感谢我的朋友 Marcus 将我指向这里,http ://tech.thereq.com/post/16479390885/loading-page-content-via-ajax-in-rails-3-1 。使用“加载”方法:

jQuery(function($){
  <% @products.each do |product| %>
    $('#calc_<%= product.id %>').hover(function() {
      $('#pid_<%= product.id %>').show().load('products/calculations/<%= product.id %>');
    }, function() {
      $('#pid_<%= product.id %>').hide()
    });
  <% end %>
});
于 2013-02-25T16:07:52.800 回答