0

我有下面的代码,我无法在每一行元素中填充总字段。

所以动态插入的每个字段都将具有相同的字段,我只需要计算该行中的字段。

这是它的 jsfiddle http://jsfiddle.net/glennmartin/3TnyR/

var LabourItems = {
   rate: null,
   hours: null,
   total: null,
   init: function(object) {
      var rate = parseInt($(object).children('.rate').val(), 10);
      // var rate = $(object).children('.rate').first();
      var hours =parseInt($(object).children('.hours').val(), 10);
      this.total = Number(rate.val()) * Number(hours.val());
      this.updateTotal(object);
   },
   updateTotal: function(object) {
      $(object).children('.total').first().attr('value', this.total)
   }
}

//reactTochange for those inputs that you want to observe
$('.hours').on("click", function() {
   jQuery.each($('.labouritems'), function(key,value){
      LabourItems.init(value);
   });
});
4

1 回答 1

1

这是您的代码工作:

var LabourItems = {
   rate: null,
   hours: null,
   total: null,
   init: function(object) {
      this.rate = parseInt($(object).children('.rate').first().val(), 10);
      // var rate = $(object).children('.rate').first();
      this.hours =parseInt($(object).children('.hours').first().val(), 10);
      this.total = this.rate * this.hours;
      this.updateTotal(object);
   },
   updateTotal: function(object) {
      $(object).children('.total').first().val(this.total || 0);
   }
}

//reactTochange for those inputs that you want to observe
$('.labouritems input').on("keyup", function() {
   $('.labouritems').each( function(key,value){
      LabourItems.init(this);
   });
});

以下是关于我所做更改的一些评论:

  • 在你的init函数中,你var用来分配你在对象上下文中声明的变量,所以我用var rateand替换var hoursthis.rateandthis.hours
  • 在您的$(object).children('.rate')and$(object).children('.hours')调用中,您需要使用.first()函数来选择第一个元素。这是因为您选择的类名可能不止一个(即使没有,您也会发现您仍然会返回一个数组)
  • $(object).children('.total').first().val(this.total || 0);:您可以val()像在其他地方使用它来检索值一样使用分配。当文本框为空时this.total返回,以确保如果出现(它是假的)然后将使用 0 代替(删除它,如果你好奇,看看会发生什么)NaN|| 0NaN
  • 您希望更改键盘事件是有道理的,所以我让您的代码使用该keydown事件。当然,您可以将其更改为您喜欢的任何内容。
  • 分配给this.total您时使用Number()which 是不必要的,因为这些值已经通过parseInt()
  • 在从DOM 选择器each()调用的函数的上下文中,提供了此迭代中的元素。因此传递实际元素,然后通过$()thisLabourItems.init(this);init$(object)

http://jsfiddle.net/3TnyR/1/

嗯,差不多就是这样!

于 2012-10-20T08:34:20.170 回答