【问题标题】:How to sum various data attr and values from inputs如何对输入中的各种数据属性和值求和
【发布时间】:2017-10-08 20:03:47
【问题描述】:

我有各种输入,每个输入通过数据属性具有不同的价格:

 <%= f.number_field :item, class: "test", :data => {:price => '10.25'}

用户可以选择他们想要的商品数量,所以我需要将选择的商品数量乘以商品的价格。

$( document ).ready(function() {
  $(".test").on('change', function() {
    a = $(".test").val() * $(".test").data("price") + "€";
    $(".resultado").html(a);
  });
});

这适用于 1 个输入,但由于我有 4 个输入,每个输入的价格不同,我需要获取其中 9 个输入的总价格。

<%= f.number_field :item, class: "test", :data => {:price => '10.25'} %>
<%= f.number_field :seconditem, class: "test", :data => {:price => '10'} %>
<%= f.number_field :thirditem, class: "test", :data => {:price => '10.75'} %>
<%= f.number_field :fourthitem, class: "test", :data => {:price => '10.50'} %>

基本上,我需要得到这个:

A: Number of items * price of each item
Sum all of the "A" values

如何修改我的脚本/类以实现此目的?

非常感谢。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您可以使用.each() 乘以返回的值.data()

    $("input[type=button]").on("click", function() {
    
      let n = 1;
    
      $(".test").each(function() {
        n *= $(this).data().price;
      });
    
      $(".resultado").html(n);
    
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    </script>
    <input type="button" value="click" />
    <div class="test" data-price="1"></div>
    <div class="test" data-price="2"></div>
    <div class="test" data-price="3"></div>
    <div class="test" data-price="4"></div>
    
    <div class="resultado"></div>

    【讨论】:

      【解决方案2】:

      假设每个项目都有不同的价格和数量,下面的重构应该可以工作。 Here's a JSFiddle with the working demo.

      $( document ).ready(function() {
        $(".test").on('change', function() {
          var total = 0;
          $.each( $('.test'), function( key, value ) {
            total += $(this).val() * $(this).data("price");
          });
          $(". resultado").html(total + "€");
        });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多