仅选择同一行内的元素

时间:2019-06-11 12:25:21

标签: jquery html

我正在使用div元素而不是td和tr来创建计算表。表格的每一行都应根据输入字段字段进行数学运算。

<div id="pricelist_table">
    <div class="table_header">
        <div id="model">Model</div>
        <div id="exw">EXW Also</div>
        <div id="vat">VAT</div>
        <div id="msrp">MSRP</div>
    </div>
    <div class="table_body">
        <div class="model">XG-C100C</div>
        <div class="exw-price">1</div>
        <div class="without-vat">1</div>
        <div class="msrp-entry"><input class="msrp-data" name="msrp-info" placeholder="enter data"></div>
    <div class="table_body">
        <div class="model">PL-AC56 KIT</div>
        <div class="exw-price">1</div>
        <div class="without-vat">1</div>
        <div class="msrp-entry"><input class="msrp-data" name="msrp-info" placeholder="enter data"></div>
    </div>
</div>

我有这样的Jquery,它捕获了所有行。

jQuery(document).ready(function( $ ){   
   $( ".msrp-data" ).keypress(function() {
    var msrp = $(".msrp-data").val();
    var vat =  25;
    var result = msrp * vat;
    $(".exw-price").html(result);
    });
});

最终的想法是仅在输入数据时才分别计算每一行。

1 个答案:

答案 0 :(得分:0)

.msrp-data的处理程序中,您可以引用$(this)来访问同一字段。要获取行中 other 字段的值,您需要对它们进行范围划分(例如,使用$(this).closest(".table_body")):

jQuery(document).ready(function( $ ){   
   $( ".msrp-data" ).keypress(function() {
    var msrp = +$(this).val();
    var vat =  25;
    var result = msrp * vat;
    $(".exw-price",$(this).closest(".table_body")).html(result);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="pricelist_table">
    <div class="table_header">
        <div id="model">Model</div>
        <div id="exw">EXW Also</div>
        <div id="vat">VAT</div>
        <div id="msrp">MSRP</div>
    </div>
    <div class="table_body">
        <div class="model">XG-C100C</div>
        <div class="exw-price">1</div>
        <div class="without-vat">1</div>
        <div class="msrp-entry"><input class="msrp-data" name="msrp-info" placeholder="enter data"></div>
    </div>
    <div class="table_body">
        <div class="model">PL-AC56 KIT</div>
        <div class="exw-price">1</div>
        <div class="without-vat">1</div>
        <div class="msrp-entry"><input class="msrp-data" name="msrp-info" placeholder="enter data"></div>
    </div>
</div>

(请注意,您还缺少第一行</div>的结尾table_body!)