繁体   English   中英

jQuery从同一个类中获取价值

[英]jQuery get value from same class

我有这个文本输入,由jquery动态生成。 但基本上,如果你从HTML POV看到,它看起来像这样:

<div class="po-row">
    <input class="po-quantity">
    <input class="po-price">    
</div>

<div class="po-row">
    <input class="po-quantity">
    <input class="po-price">    
</div>

<div class="po-row">
    <input class="po-quantity">
    <input class="po-price">    
</div>

现在,我想做这个计算:

每个po-row必须有subtotal ,按po-quantity * po-price

每行的所有小计将总计为总计。 这是我所做的,但仅适用于第一行:

$(".po-row").each(function(){
    $(".po-price").blur(function(){
        var quantity = $(".po-quantity").val();
        var price = $(".po-price").val();
        var subtotal = quantity * price;
        $(".total").text(subtotal);
    });         
});

在这种情况下如何使each文字的jquery工作? 谢谢

改变each的顺序和blur 这将使计算在.po-price元素的每个blur事件上运行。

$(".po-price").blur(function() {
    var total = 0;
    $(".po-row").each(function() {
        var quantity = $(".po-quantity").val();
        var price = $(".po-price").val();

        total += quantity * price;
    });
    $(".total").text(total); // Update the total
});

您需要修改逻辑以计算blur()处理程序中的所有行,并将选择器限制为循环的当前行中的价格和数量字段。 尝试这个:

$(document).on('blur', '.po-price', function () {
    var subtotal = 0;
    $('.po-row').each(function() {
        var quantity = $(this).find(".po-quantity").val();
        var price = $(this).find(".po-price").val();
        subtotal += quantity * price;
    });
    $(".total").text(subtotal);
});

示例小提琴

请注意,我在document中使用了document作为主要选择器。 对于您的工作代码,您应该使用.po-price最接近的父元素,该元素在页面加载时在DOM中可用。

尝试使用以下语句:first和:last确定输入:

  var total = 0;
  $('.po-row').each(function() {
    total += $(this).find('input:first').val() * $(this).find('input:last').val();
  });
  alert(total);

 window.calc = function() { var total = 0; $('.po-row').each(function() { total += $(this).find('input:first').val() * $(this).find('input:last').val(); }); alert(total); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="po-row"> <input class="po-quantity"> <input class="po-price"> </div> <div class="po-row"> <input class="po-quantity"> <input class="po-price"> </div> <div class="po-row"> <input class="po-quantity"> <input class="po-price"> </div> <button type="button" onclick="calc()">Calculate</button> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM