总结来自不同的功能 - Javascript

时间:2012-04-05 01:57:27

标签: javascript function variables sum new-operator

我需要能够创建一个单独的函数,从2个不同函数中的变量创建一个总数。

    function addToy1()
{
var i = document.getElementById("qty_toy1");
var qtytoy1 = i.options[i.selectedIndex].text;
var qtytoy1tot = qtytoy1 * 26.99;
var generateTableToy1="<table width=\"210px\" border=\"0\">"
                    +"  <tr>"
                    +"    <td width=\"140\">Optimus Prime</td>"
                    +"    <td width=\"25\">x " + qtytoy1 + "</td>"
                    +"    <td width=\"45\">&pound;" + qtytoy1tot + "</td>"
                    +"  </tr>"
                    +"</table>";

document.getElementById("toy1_add").innerHTML=generateTableToy1;

}

function addToy2()
{
var i = document.getElementById("qty_toy2");
var qtytoy2 = i.options[i.selectedIndex].text;
var qtytoy2tot = qtytoy2 * 14.39;
var generateTableToy2="<table width=\"210px\" border=\"0\">"
                    +"  <tr>"
                    +"    <td width=\"140\">Bumblebee</td>"
                    +"    <td width=\"25\">x " + qtytoy2 + "</td>"
                    +"    <td width=\"45\">&pound;" + qtytoy2tot + "</td>"
                    +"  </tr>"
                    +"</table>";

document.getElementById("toy2_add").innerHTML=generateTableToy2;


}

使用此代码,我需要将两个变量“qtytoy1tot”和“qtytoy2tot”相加。我是Javascript的新手。请尽可能帮助您。感谢。

1 个答案:

答案 0 :(得分:0)

这里有很多选择。最直接的是Amit在评论中建议的,只返回每个方法的总数。这可能会也可能不会起作用,具体取决于您计划如何使用这些方法。以下内容应该适用于您的目的。

function ToyBox() {
    this.total = 0;
}

ToyBox.prototype.addToy1 = function() {
    var i = document.getElementById("qty_toy1");
    var qtytoy1 = i.options[i.selectedIndex].text;
    var qtytoy1tot = qtytoy1 * 26.99;
    this.total += qtytoy1tot;
    var generateTableToy1="<table width=\"210px\" border=\"0\">"
                        +"  <tr>"
                        +"    <td width=\"140\">Optimus Prime</td>"
                        +"    <td width=\"25\">x " + qtytoy1 + "</td>"
                        +"    <td width=\"45\">&pound;" + qtytoy1tot + "</td>"
                        +"  </tr>"
                        +"</table>";

    document.getElementById("toy1_add").innerHTML=generateTableToy1;
        };

ToyBox.prototype.addToy2 = function() {
    var i = document.getElementById("qty_toy2");
    var qtytoy2 = i.options[i.selectedIndex].text;
    var qtytoy2tot = qtytoy2 * 14.39;
    this.total += qtytoy2tot;
    var generateTableToy2="<table width=\"210px\" border=\"0\">"
                        +"  <tr>"
                        +"    <td width=\"140\">Bumblebee</td>"
                        +"    <td width=\"25\">x " + qtytoy2 + "</td>"
                        +"    <td width=\"45\">&pound;" + qtytoy2tot + "</td>"
                        +"  </tr>"
                        +"</table>";

    document.getElementById("toy2_add").innerHTML=generateTableToy2;
};

var toyBox = new ToyBox();
toyBox.addToy1();
toyBox.addToy2();
console.log(toyBox.total);

请记住,你真的只有一个函数,你应该将变量部分作为参数传递给函数,但我认为这可能超出了这个问题的范围。