使用 jQuery,我在具有类似类名“score”的字段中有浮点值,我只想创建一个函数,将这些字段中的所有浮点值相加并将结果分配给“<强>field5”。
<input id="field1" type="text" class="score">2.5</input>
<input id="field2" type="text" class="score">6.02</input>
<input id="field3" type="text" class="score">1</input>
<input id="field4" type="text" class="score">4.03</input>
<input id="result" type="text" class="result"></input>
我编写了下面的脚本,但即使该函数执行它也不起作用。
$(.score).on('change',function(){
var total = 0
$(this).each(function(){
total += this.value;
});
});
$('#result').val(total);
});
最佳答案
您的代码中存在很多问题:
JS:
$(".score").on('keyup', function () {
var total = 0
$(".score").each(function () {
total += parseFloat(this.value);
});
$('#result').val(total);
});
HTML
<input id="field1" type="text" class="score" value="1"/>
<input id="field2" type="text" class="score" value="1.2"/>
<input id="field3" type="text" class="score" value="1.4"/>
<input id="field4" type="text" class="score" value="3.1"/>
<input id="result" type="text" class="result" value=""/>
演示:http://jsfiddle.net/GCu2D/839/
- input 是一个自闭合标签。您应该像本示例中那样使用它
- 您应该迭代
$(".score")
而不是$(this)
来获取所有输入值。后者仅给出当前输入的值。 - 使用parseFloat将字符串类型转换为float类型。默认情况下,您从
.value
获取字符串值。为了添加它们,您需要将它们转换为 float - 您的选择器
$(.score)
无效。使用$(".score")
。 $('#result').val(total);
应位于事件处理程序内。
关于javascript - jQuery:如何使用类名在多个字段中添加浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32152749/