0

問題がある以下のコードを取得しました。最初のインスタンスを除いて、「Labouritems」のインスタンスの「合計」金額を計算できません。その後は、計算することができません。

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);
   });
});
4

2 に答える 2

1

を呼び出すことはないため、コードに「インスタンス」はありませんnew

LabourItemsオブジェクトとして扱われるようにするには、次のように宣言します。

function LabourItems(object) {
     return {
         rate: null,
         ...
     }
});

次にnew LabourItems(this)、イベント ハンドラーで使用します。

別の方法として (各インスタンスは独自のコピーを含むのではなく、メソッドのコピーを共有するため、より効率的です)、通常のプロトタイプ宣言を使用します。

function LabourItems(object) {
     this.rate = null,
     ...
};

LabourItems.prototype.init = function() {
    ...
};

LabourItems.prototype.updateTotal = function() {
    ...
};

上記のように使用new LabourItems(this)します。

于 2012-10-20T22:06:37.973 に答える
1

それは簡単です: 'Labouritems' のインスタンスをLabouritems作成しません。オブジェクトは 1 つだけです。

于 2012-10-20T22:06:25.957 に答える