如何在javascript中强制添加而不是连接 [英] How to force addition instead of concatenation in javascript
问题描述
我正在尝试像这样在我的 javascript 中添加所有卡路里含量:
I'm trying to add all of the calorie contents in my javascript like this:
$(function() {
var data = [];
$( "#draggable1" ).draggable();
$( "#draggable2" ).draggable();
$( "#draggable3" ).draggable();
$("#droppable_box").droppable({
drop: function(event, ui) {
var currentId = $(ui.draggable).attr('id');
var total = 0;
data.push($(ui.draggable).attr('id'));
if(currentId == "draggable1"){
var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
}
if(currentId == "draggable2"){
var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
}
if(currentId == "draggable3"){
var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
}
if ( typeof myInt1 === 'undefined' || !myInt1 ) {
myInt1 = parseInt(0);
}
if ( typeof myInt2 === 'undefined' || !myInt2){
myInt2 = parseInt(0);
}
if ( typeof myInt3 === 'undefined' || !myInt3){
myInt3 = parseInt(0);
}
total = parseFloat(myInt1 + myInt2 + myInt3);
$('#response').append(total);
}
});
$('#myId').click(function(event) {
$.post("process.php", ({ id: data }), function(return_data, status) {
alert(data);
//alert(total);
});
});
});
不是添加变量,而是将它们连接起来.我已经尝试过使用 parseInt、parseFloat 和 Number,但我仍然只是得到了连接而不是加法.请查看http://maureenmoore.com/momp_112412/121912_800.html
Instead of adding the variables they get concatenated. I've tried using parseInt, parseFloat, and Number but I still just get concatenation and not addition. Please look at the view source at http://maureenmoore.com/momp_112412/121912_800.html
推荐答案
您的代码连接三个字符串,然后将 result 转换为数字.
Your code concatenates three strings, then converts the result to a number.
您需要通过在每个变量周围调用 parseFloat()
将 每个变量 转换为数字.
You need to convert each variable to a number by calling parseFloat()
around each one.
total = parseFloat(myInt1) + parseFloat(myInt2) + parseFloat(myInt3);
这篇关于如何在javascript中强制添加而不是连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!