如何在动态表中定位同一行中的元素

How do I locate elements in the same row as another in a dynamic table?

本文关键字:一行 元素 动态 定位      更新时间:2023-09-26

我正在制作一个页面,其中包含一个带有添加行按钮的表。它是一个供用户输入数据的表,最终将提交到数据库。

目前,我在每一行都有一个价格和数量字段。当它们中的任何一个发生变化时,我想计算总数并将其写入另一个单元格。

这是我的事件处理程序(封装在$(document).ready()中):

$(".quantity_input, .price_input").change(function () {
    console.log(this.value);
    cal_total();
});

这是我当前的代码:

function cal_total() {
    if (isNaN(parseFloat(this.value))) {
      alert("You must enter a numeric value.");
      this.value = "";
      return;
    }
    var cell = this.parentNode;
    var row = cell.parentNode;
    var total = parseFloat($("#items_table tr").eq(row.index).find("td").eq(3).find("input").first().val()) * parseFloat($("#items_table tr").eq(row.index).find("td").eq(4).find("input").first().val());
    if (!isNaN(total)) {
      $("#items_table tr").eq(row.index).find("td").eq(5).html(total.toFixed(2));
    }
}

这就是输入的样子:

 <input type='text' class='fancy_form quantity_input' name='quantities[]' size='4' style='text-align:center;border-bottom:none;'>

除了我最初的问题之外,该活动从未被解雇。有人知道为什么吗?

但更重要的是,这是检索值的最佳方式吗?我真的不这么认为,但我想不出比这更聪明的办法了。

谢谢!

您必须将参数传递给calc_total以定义输入或tr

试试这个代码

 
$(".quantity_input, .price_input").change(function () {
   $(".quantity_input, .price_input").change(function () {
       cal_total(this);
        });
   });
   function cal_total(elem){
     var row=$(elem).closest("tr")
	 var quantity=row.find(".quantity_input").val()-0
	  var price=row.find(".price_input").val()-0
	  var total=quantity * price
	  row.find(".totl_input").val(total)
   }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
   <tr>
     <td>
	   <input  class="quantity_input" />
	 </td>
	 <td>
	   <input  class="price_input" />
	 </td>
	 <td>
	   <input  class="totl_input" />
	 </td>
   </tr>
   <tr>
     <td>
	   <input  class="quantity_input" />
	 </td>
	 <td>
	   <input  class="price_input" />
	 </td>
	 <td>
	   <input  class="totl_input" />
	 </td>
   </tr>
   <tr>
     <td>
	   <input  class="quantity_input" />
	 </td>
	 <td>
	   <input  class="price_input" />
	 </td>
	 <td>
	   <input  class="totl_input" />
	 </td>
   </tr>
   </table>