【问题标题】:Javascript and Variable assistanceJavascript 和变量辅助
【发布时间】:2014-04-26 07:37:09
【问题描述】:

(改写之前的问题)所以这是作业:

首先,您必须计算包裹重量的成本。用户将在文本字段中输入包裹的总重量。日程安排如下……

0 – 150 磅 $20.00 每磅 | 151 – 300 磅 $15.00 每磅 | 301 – 400 磅每磅 10.00 美元 不允许用户输入 400 的权重。如果输入,则将红色错误消息输出到 div#results 并从函数中“返回”。

接下来,用户将选择一个折扣金额(无论出于何种原因,都无所谓)。您将需要应用选择的任何折扣金额。 (50% 折扣,20% 折扣,无)。

这是我到目前为止所做的。变量还没有声明,只是写进去了。

function calcTotal() {

var msg;
var weight = parseInt( document.getElementById("weight").value );
var discount;
var total;

if( weight >= 0 && weight <= 150 ) {

    total = weight * 20 
}   
else if( weight >150 && weight <= 300 ) {

    total = weight * 15 
}   
else if( weight >300 && weight <= 400 ) {

    total = weight * 10 
}

if( document.getElementById("50%").selected == true ) {

total = total * 0.50;
}

if( document.getElementById("25%").selected == true ) {

total = total * 0.25;
}

if( document.getElementById("none").selected == true ) {

total = total;
}

到目前为止,这有点正确吗?

似乎无法根据用户的选择弄清楚如何应用折扣。折扣是 3 个单选按钮。我需要为每个单选按钮应用一个 id 吗?

【问题讨论】:

  • 当您大声说“如果重量大于零或小于 150”时,您暗示“或重量小于 150”。 JavaScript 不太擅长理解含义,你必须告诉它你想要什么;)
  • 在您的代码中,如果 weight >= 0,它将始终输入第一条语句(因为它始终为真)-您希望限制在 0-150 范围内,您需要确保两者条件为真 (w >= 0 AND w
  • 我还将权重和折扣作为参数传递给函数;并且不要忘记处理 w 400 时的情况(并相应地设置消息) - 最后返回 msg,瞧 :)
  • @blurfus “我还将权重和折扣作为参数传递给函数。”你这是什么意思?谢谢。
  • 查看我的答案

标签: javascript variables if-statement var


【解决方案1】:

我做了一个小提琴,你应该能够很快了解正在发生的事情。

http://jsfiddle.net/a58rR/3/

我使用了一点 jQuery 来获取 UI 元素上的绑定。

我希望这不是为了上课,你抄这个批发! ;)

基本上,我将您的所有层级定价放在一个对象中。

Tiers = [{
    nPrice: 20,
    nWeightMin: 1,
    nWeightMax: 150
}, {
    nPrice: 15,
    nWeightMin: 151,
    nWeightMax: 300
}, {
    nPrice: 10,
    nWeightMin: 301,
    nWeightMax: 400
}]; 

然后,您的函数将根据输入的重量和选择的折扣进行计算,确定层级,验证重量,如果超出范围,使用消息更新 UI,计算最终价格并应用任何折扣,然后更新 UI总价:

function calculatePrice() {
    console.log('Begin Calc');
    var _nW = document.getElementById('nParcelWeight').value * 1;
    var _nD = document.getElementById('aDiscounts').value * 1;
    var _nP = 0;
    var nTotalPrice = 0;
    var _TotalPrice = document.getElementById('nPrice');
    var _nMaxWt = Tiers[Tiers.length - 1].nWeightMax; 
    // Using the last Tier keeps the max weight dynamic no matter how many tiers you add as long as they are in order

    console.log('Max Weight: ' + _nMaxWt);
    console.log('Weight: ' + _nW);
    console.log('Discount: ' + _nD);

    if (isNaN(_nW) || _nW < 1 || _nW > _nMaxWt) {

        // Throw/Display an out of range error here  
        console.log('Yep, out of range');
        document.getElementById('uiFeedback').innerHTML = 'The number is out of range.';
    } else {
        // reset if valid
        document.getElementById('uiFeedback').innerHTML = '';
    }

    // Find Tier
    for (var i = 0; i < Tiers.length; i++) {
        console.log('we are in loop:' + i);
        if (_nW >= Tiers[i].nWeightMin && _nW <= Tiers[i].nWeightMax) {
            _nP = Tiers[i].nPrice;
            break;
        }
    }
    console.log('Tier: ' + i);
    console.log('Price: ' + _nP);

    // Calculate Discount
    if (_nD != 1) _nD = 1 - _nD; // (20%==.20, but that would be .80 of the Price, etc)

    // Calc Price
    nTotalPrice = (_nP * _nW * _nD);
    _TotalPrice.value = nTotalPrice;
}

html 看起来像这样:

<div id='uiFeedback'></div>Parcel Weight:
<input id='nParcelWeight' value='0'>Discount:
<select id='aDiscounts'>
    <option value='1'>none</option>
    <option value='.2'>20%</option>
    <option value='.5'>50%</option>
</select>
<hr>Price:
<input id='nPrice'>

您的 CSS 至少可以为您的消息添加颜色:

#uiFeedback {
    color: red;
    font-weight: bold;
}

以下是绑定,您可以使用内联 onChanges 或原始 js 附加事件来完成:

$(function () {
    $('#nParcelWeight,#aDiscounts ').on('change', function () {
        calculatePrice();
    });
})

【讨论】:

  • 这与我们学到的不同,尽管它看起来很有希望。有什么办法可以把我的整个代码发给你,向你展示我们是如何学习的?我收到这个令人沮丧的错误消息,说我的函数没有定义。不明白为什么,也无法解决问题。
  • @user3389685 当然。 gmail dot com 的 williambq。
【解决方案2】:

首先你需要使用 && (AND) 而不是 || (或)因为您希望同时满足两个条件而不仅仅是一个。第一个 IF 语句将值 -1000 处理为 TRUE(以及任何其他值,因为您的间隔是从 0 到无穷大加上从负无穷大到 150),因为它满足第一个条件的第二部分。

其次,公式是正确的,但您必须将百分比转换为 0-1 区间。 100% = 1、0% = 0 和 x% = x/100。那么它应该可以正常工作。

最后要做的是你需要将值传递到你的函数中:

function calcTotal(weight, discount) {
    // do the calculation with passed values, you do not need to declare them here anymore
}

或者您需要在该函数内部设置值,例如:

function calcTotal() {
    var discount = $("#inputField").val();  // using jQuery, where inputField is element
                                            // from which the value is taken e.g. < input >
    ...
}

要显示最终输出,请将其添加到您的函数中:

$("body").append("<div id='output'>" + output + "</div>"); // using jQuery, watch for single/double quotes

并用 css 将其设置在中心:

#output {
    position: absolute;
    width: 200px;
    height: 200px;
    left: 50%;
    margin-left: -100px;
    top: 200px;
}

【讨论】:

  • 我现在想添加消息“您的总成本是:......”显示总成本加上折扣(基于用户选择的内容),输出带有美元符号。
  • 在哪里添加消息?
  • 当用户点击按钮进行计算时,将其作为结果/输出添加到网页中。
  • doh,将其添加到网页的何处以及如何添加?作为为此准备的某些现有元素的值?还是动态创建新元素并将其放置在网页上的某个位置,显示为警报还是模式窗口?
  • 就这样它出现在网页的中心。像“
    你的总成本是:$”+总
猜你喜欢
  • 2013-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-24
  • 1970-01-01
  • 2016-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多