Javascript 无法在每个div元素实例上填充字段
我有下面的代码,我无法在每一行元素中填充total字段 所以动态插入的每个字段都有相同的字段,我只需要计算该行中的字段 这是它的JSFIDLEJavascript 无法在每个div元素实例上填充字段,javascript,jquery,Javascript,Jquery,我有下面的代码,我无法在每一行元素中填充total字段 所以动态插入的每个字段都有相同的字段,我只需要计算该行中的字段 这是它的JSFIDLE 以下是您的代码: var LabourItems = { rate: null, hours: null, total: null, init: function(object) { this.rate = parseInt($(object).children('.rate').first().val(), 10);
以下是您的代码:
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-rate
替换为var-hours
和this.rate
this.hours
- 在
和$(对象).children('.rate')
调用中,需要使用$(对象).children('.hours')
函数来选择第一个元素。这是因为您选择的类名可能不止一个(即使没有,您仍会发现返回一个数组).first()
$(object.children('.total').first().val(this.total | | 0)代码>:您可以使用
赋值,就像在其他地方使用它检索值一样val()
在文本框为空时返回this.total
,因此NaN
确保如果出现| | 0
(它是错误的),则将使用0(如果您好奇,请删除它并查看发生了什么)NaN
- 您希望更改键盘事件是有道理的,因此我让您的代码使用
事件。当然,你可以把它改成你喜欢的任何东西keydown
- 当分配给
时,您使用的是this.total
,这是不必要的,因为这些值已经通过Number()
parseInt()
- 在从
DOM选择器$()
提供此迭代中的元素。所以调用的
函数的上下文中,此each()
将实际元素传递到LabourItems.init(this)
,然后通过init
$(对象)
嗯,差不多就是这样 这是一个多么好的回答啊,我的朋友,如果你理解我的意思,你现在就教我如何钓鱼。实际上,在JSFIDLE上,它在keydown上起作用,但在我的应用程序“rails”中,它只在劳动项目的第一个实例上起作用,而且只有在我离开现场时才起作用。难道是这个部门的结构容纳了劳工?此外,我还在表单中动态添加labouritem字段的实例,不确定这是否有帮助。
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);
});
});