如何在JavaScript中强制加法而不是串联 [英] How to force addition instead of concatenation in javascript

查看:110
本文介绍了如何在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 <<中查看视图源/p>

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

推荐答案

您的代码将三个字符串连接起来,然后将结果转换为数字.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆