我得到了以下代码,我遇到了问题。 除了第一个实例之外,我无法计算'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);
});
});
答案 0 :(得分:1)
这很容易:你没有创建任何'Labouritems'的实例,你只有一个Labouritems
对象。
答案 1 :(得分: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)
。