【问题标题】:javascript, html form and array arithmeticsjavascript、html 表单和数组算法
【发布时间】:2015-06-09 08:52:54
【问题描述】:

我正在尝试为带有网页的零售商制作一个简单的脚本——我们有三种水果——AppleBananaOrange

两种品质——苹果(坏和好)、香蕉(坏和好)和橙子(坏和好)……在所有情况下都是劣质的。

所以我有两种质量选择——好的和坏的

数量从 1 到 10

我用数组做了类似的事情,但它只适用于两个变量而不是三个。我想要的最终结果是——

我选择苹果 > 好 > 5 个单位 = 5*4 = 20

Form Option - select (apple,banana, orange), select(good, bad) , select(number of units)

这就是我所做的

    costperfruit = new Array(4,5,6, 7,8,9);

    function setcost()
    {
        cpp = costperfruit[document.frm.colour_fruit.value*1-1];
        sum = cpp*document.frm.numberUnits.value;
        sum += "";
        pos = sum.indexOf(".");
        if (pos>0)
        {
            sum = sum.substring(0,pos+3);
            if (sum.indexOf(".")+3>sum.length)
                sum += "0";
        }
        else
            sum += ".00";

        document.frm.cost_per_fruit.value = cpp;
        document.frm.total_sum.value = sum;
    }

有了这个,我可以轻松地将单位数量与水果成本相乘。绿色选项在每种情况下都是劣质的,因此售价为 3、5、7,比红色、黄色、红色橙色低 1 美元

我想在选择时看到价格--

橙色> 坏> 3 = 7*3 = 21 苹果> 坏 > 4 个单位 > 3*4 = 12

我在 HTML 中使用选择表单。

【问题讨论】:

    标签: javascript html forms


    【解决方案1】:

    您的解决方案可以工作,但很难维护。我建议您使用一些数据结构来存储产品价格:

    var prices = {
        "apple": {
            "good": 4,
            "bad": 5
        }
        "banana": {
            "good": 6,
            "bad": 7
        }
        "orange": {
            "good": 8,
            "bad": 9
        }
    }
    

    然后,如果您想为特定商品选择价格,您只需使用:

    prices["apple"]["bad"]
    

    【讨论】:

    • 让我运行它并尝试使用 html 标签修复我的解决方案。一定会让你知道的。我对 javascript 的经验很少。
    【解决方案2】:

    根据上面 survoc 的建议,我添加了一些代码来处理 Object Literal。

    看看下面的 Fiddle 看看是否有帮助。

    https://jsfiddle.net/f79vj0s3/

    注意我改变了对象:

    // Object Literal
    var produce = {
        "Apple": {
            "good": 
                {
                "qty" : 5, 
                "cost" : 2
              },
            "bad": 
                {
                "qty" : 3, 
                "cost" : 1
              }
        },
        "Banana": {
            "good": 
                {
                "qty" : 6, 
                "cost" : 3
              },
            "bad": 
                {
                "qty" : 4, 
                "cost" : 2
              }
        },
        "Orange": {
            "good": 
                {
                "qty" : 5, 
                "cost" : 3
              },
            "bad": 
                {
                "qty" : 3, 
                "cost" : 1
              }
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2011-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2020-09-30
      • 1970-01-01
      相关资源
      最近更新 更多