1

这就是我正在做的事情。

我有一组 div。每组 div 可以包含一个节标题和一个项目列表。每个项目都有一个与之相关的价格。因此,拆除部分下的项目 1 的价格为 150.00。拆除部分下的项目 2 的价格为 200.00。每个项目旁边是一个输入字段,用户可以输入数值。然后将该值乘以项目价格。所以在项目 1(150.00) 旁边是我输入 2 的字段。然后在下一个 div 中显示总数。所以 150.00 x 2 = 300.00。

我可以为该部分下的每个项目执行此操作。然后,我将整个项目汇总为各个部分旁边的一个全球价格。

这是我正在做的一个示例:

$(document).ready(function() {
  $(".demolition_num").each(function() {
    $(this).keyup(function(){
      calculateDemSum();
    });
  });
});


function calculateDemSum() {
   var sum = 0;
   $(".demolition_num").each(function(){
     if(!isNaN(this.value) && this.value.lenth != 0){
        var unitCost = $(".unit_cost1").text();
        var _parent = $(this).parent();
        var total = _parent.prev().html();
        sum += parseFloat(this.value * total);
        var subtotal = this.value * total;
        $(_parent).next().html(this.value * total);
     }
     else if (this.value.length !=0){
     }
   });

   $(".cost1").text(sum.toFixed(2));
   $("#cost1").val(sum.toFixed(2));
}

您可以在此处查看所有代码:http: //jsfiddle.net/pmetzger/Xeu2T/3/

正如您在 jquery 中看到的那样,现在我必须独立于其他部分调用每个部分,因为我不想计算所有字段,只是我正在修改的字段。

所以问题是,我是否可以避免将每个部分的输入类型 id 添加为触发计算并确保正确放置总计的键?

注意:此代码可以重复,但关联的数据会有所不同。因此,在下一个客户列表中,它可能不是 Demolition,而是 Demo 等等。

任何帮助将不胜感激。

4

1 回答 1

0

首先是几个指针:

  1. 您不需要在each()循环中绑定事件,只需将其绑定到标准选择器即可绑定到适合该选择器的所有元素。
  2. 您还有多个<tr>具有相同 id 的元素。
  3. 您不需要size隐藏标签上的属性

新的工作小提琴和代码:

$(document).ready(function()
{
    // Bind the event
    $("#calc").on("keyup", "input[type='text']", function()
    {
        calculateSum(this);
    });
});

function calculateSum(element)
{
    var sum = 0;
    var $this = $(element);
    var targetClass = $this.attr("class");

    // Process each element with the same class
    $("." + targetClass).each(function()
    {
        var thisVal = $(this).val();

        // Count invalid entries as 0
        if(isNaN(thisVal) || thisVal.length === 0)
        {
            thisVal = 0;
        }
        else
        {
            thisVal = parseFloat(thisVal);
        }

        // Get the unit cost and calculate sub-total
        var unitCost = parseFloat($(this).parent().prev("td.unit_cost").text());
    var subTotal = thisVal * unitCost;
    sum += subTotal;
        $(this).parent().next("td").text(subTotal);
    });

    var $item = $this.closest("tr").prevAll(".item").first();
    $item.find("input.section_cost").val(sum.toFixed(2));
    $item.find("td.section_cost").text(sum.toFixed(2));
}

请注意,我已经稍微修改了您的 HTML - 我更改了多个<tr id="item">以使用类,我移动了这些行以更好地定位您的小节总计,我将类添加到小节总计(隐藏输入和显示值),我添加了一个类到您的单位值字段,我在表中添加了一个 id。

于 2013-05-02T00:10:06.220 回答