jquery – 如何强制添加而不是连接在javascript - 代码日志

jquery – 如何强制添加而不是连接在javascript

参见英文答案 > How to force JS to do math instead of putting two strings together                                    7个答案                                我想添加所有的卡路里内容在我的javascript像这样:

$(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查看来源

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

您需要通过每个变量调用parseFloat()将每个变量转换为一个数字。

total = parseFloat(myInt1) + parseFloat(myInt2) + parseFloat(myInt3);
http://stackoverflow.com/questions/13953939/how-to-force-addition-instead-of-concatenation-in-javascript

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:jquery – 如何强制添加而不是连接在javascript