【问题标题】:javascript_include_tag not working properly inside a partial in Ruby on Railsjavascript_include_tag 在 Ruby on Rails 的部分内部无法正常工作
【发布时间】:2012-04-26 08:09:54
【问题描述】:

我正在使用 simple_nested_form,我的客户账单表格中有这个

<%= simple_nested_form_for @customer_bill do |f| %>
 <%= f.error_messages %>

 <%= f.label :employee_id %>
    <%= f.collection_select :employee_id, Employee.all,:id,:name, {:prompt => "Select Employee"}, :style => 'width:205px;' %><br />

            <%= f.label :date %>
            <%= f.datepicker :date, :dateFormat => 'dd MM, yy',  :showOn => "both", :buttonImage => "../assets/calendar.gif", :buttonImageOnly => true, :changeMonth => true, :changeYear => true, :placeholder => "Click on the Calender" %><br/>          

 <p><%= f.link_to_add "Add Product", :customer_bill_line_items %> </p>
  <p><%= f.submit %></p>
<% end %>

点击“添加产品”后,会呈现以下部分

 <%= javascript_include_tag 'calculations' %>
     <hr/> 
    <%= f.hidden_field :user_id, :value => current_user.id %>
    <%= f.hidden_field :customer_bill_id %>

    <%= f.label :product_id %>
    <%= f.collection_select :product_id,Product.all,:id,:title, :prompt => "Select a Product", :style => 'width:150px;' %>&nbsp;&nbsp;&nbsp;<%= f.link_to_remove "Remove Product"%>
    <br/>

     <p class="fields">
<%= f.input :price, :class =>"price" %>
<br/>
<%= f.input :quantity, :class =>"qty" %><br/>

<%= f.input :amount, :class =>"amount"%><br/>
</p>

我的 Calculations.js 中有这个

jQuery(document).ready(function(){
jQuery(".price, .qty").keyup(function() {
        var p = jQuery(".price").val();
        var q = jQuery(".qty").val();
        jQuery(".amount").val(q * p);
    });
});

现在问题是第一次我点击“添加产品”并输入“价格”和“数量”,金额在 js 文件中计算并显示在“金额”字段中,然后我点击添加产品第二次,第一次的计算被渲染,似乎js文件在每个“金额”字段中显示第一次计算的值

似乎是什么问题?每次我调用部分时,我该怎么做才能进行正确的计算?急需帮助。提前致谢

【问题讨论】:

    标签: jquery ruby-on-rails nested-forms ruby-on-rails-3.2 renderpartial


    【解决方案1】:

    第二次呈现“添加产品”部分后,页面上的某些元素具有重复的 id 值(priceqtyamount)。这是无效的 HTML,jQuery 将无法判断您要将 keyup 绑定到哪些。

    尝试重写你的 partial 和 jQuery 来避免这个问题。要么生成正确的唯一 ID,要么将您的 keyup 挂钩到不同的属性(可能是一个类?)。如果您选择后者,您还可以考虑将 jQuery 作为 live 调用放入页面,而不是为每个新产品添加新的 keyup 绑定。

    【讨论】:

    • 感谢 Chowlett 的建议,我实际上是新手,一直在关注 railcasts 和其他论坛来实现这一点。你能告诉我如何创建唯一的 id 吗??
    • @Chowlett-i 将 'id' 替换为 'class',问题基本解决。现在从第二次调用partial,第一次partial计算的金额来了!!不知道该怎么做。有什么亮点吗??
    • 我也用live代替了keyup,没用!
    • 您需要确保根据字段的正确实例进行计算。不要在句柄中重新调用 jQuery('.price'),而是从 this 遍历 DOM,以确保您获得同一父级的子级 .price.qty
    • Fiddle for you - 希望这能把事情弄清楚一点。 DOM遍历的文档是here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多