我有一个循环,使用自定义属性<li>
生成filesize
,现在我想用此类搜索所有<li>
并对值求和,但它会返回两个值旁边彼此而不是总结价值观。
https://jsfiddle.net/y6yLL0yv/1/
var myElements = jQuery(".fileRess");
var sumoffilessize = 0;
for (var i = 0; i < myElements.length; i++) {
var valueofthis = myElements.eq(i).attr("sizefile");
var valuetostr = valueofthis.toString();
var sumoffilessize = (valuetostr + sumoffilessize);
}
alert(sumoffilessize);
HTML:
<div id="fileInfo1">
<div style="clear:both;padding:5px;" class="fileRess" sizefile="206519" id="fileres_0">
<input size="1" type="file" class="file" name="attach[]" id="attacher" style="display:none" multiple="" value="undefined">206519 </div>
<div style="clear:both;padding:5px;" class="fileRess" sizefile="290284" id="fileres_1">
<input size="1" type="file" class="file" name="attach[]" id="attacher" style="display:none" multiple="" value="undefined">290284 </div>
</div>
<div id="result"></div>
答案 0 :(得分:0)
在对其进行求和之前,尝试使用sizefile attribute
将您从parseInt(numberString)
获得的字符串转换为数字
var myElements = jQuery(".fileRess");
var sumoffilessize = 0;
for (var i = 0; i < myElements.length; i++) {
sumoffilessize += parseInt(myElements.eq(i).attr("sizefile")
}
alert(sumoffilessize);
如果你不转换它,那么string concatenation
将会发生,因为+
对于字符串连接和数学加法是常见的。它遇到单个string operand
时会进行字符串连接。
答案 1 :(得分:0)
从DOM读取的值是字符串。如果任何操作数是字符串,+
将作为字符串连接运算符。
从DOM读取时,需要将字符串转换为Number,然后对其执行算术运算。
将字符串转换为数字有很多选项。见How do I convert a string into an integer in JavaScript?
var total = 0;
// Iterate over all the elements having the `fileRess` class
$('.fileRess').each(function () {
// Get the attribute value from DOM
// Cast to Number by using unary `+` operator
// Add to the `total` variable
total += +$(this).attr('sizefile');
});
$('#result').text('Total: ' + total);
&#13;
#result {
margin: 10px;
color: green;
font-weight: bold
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="fileInfo1">
<div style="clear:both;padding:5px;" class="fileRess" sizefile="206519" id="fileres_0">
<input size="1" type="file" class="file" name="attach[]" id="attacher" style="display:none" multiple="" value="undefined">206519 </div>
<div style="clear:both;padding:5px;" class="fileRess" sizefile="290284" id="fileres_1">
<input size="1" type="file" class="file" name="attach[]" id="attacher" style="display:none" multiple="" value="undefined">290284 </div>
</div>
<div id="result"></div>
&#13;
var total = 0;
// Iterate over all the elements having the `fileRess` class
$('.fileRess').each(function () {
// Get the attribute value from DOM
// Cast to Number by using unary `+` operator
// Add to the `total` variable
total += +$(this).attr('sizefile');
});
console.log(total);
答案 2 :(得分:0)
您只需要替换
var valuetostr = parseInt(valueofthis.toString());
与
Conversion failed when converting the varchar value '--' to data type int