我有几个<input>元素,如下所示:
<input id="hosts" name="250" class="hostselector" type="number" min="0" max="999" value="0" />我想将(用户输入的)值与我存储在name中的值相乘。
现在页面上有几个元素,都是通过class="hostselector"实现的。我想要得到所有值的总和,所以在某种意义上:
(value * name) + (value * name) + .... every single element with that class.我该如何使用jquery做到这一点呢?
发布于 2011-07-07 23:50:42
var total = 0;
$(".hostselector").each(function() {
total+= parseInt(this.value, 10) * parseInt($(this).attr("name"), 10);
});这将遍历类为.hostselector的所有元素,将当前值乘以name属性(它是一个字符串,因此使用parseInt)的值,并维护所有元素的运行总数。
这是一个显示它工作的example fiddle (只需单击按钮即可查看最终结果)。
发布于 2011-07-07 23:53:22
它应该是这样的:
var total = 0;
$('.hostselector').each(function() {
total += parseInt($(this).val(), 10) * parseInt($(this).attr('name'), 10);
})"total“变量保存您要查找的数字。
parseInt部分或多或少是可选的,javascript在没有它的情况下仍然会返回正确的结果,但是因为.val()和.attr()返回字符串,所以这样做是正确的。
发布于 2011-07-07 23:51:06
试试这个:
var sum = 0;
$.each('.hostselector', function(i ,item){
sum += $(item).val();
// or sum += $(item).attr("Your_Attribute_here");
});
alert(sum);https://stackoverflow.com/questions/6613294
复制相似问题