if语句刷新javascript

时间:2017-07-18 16:55:57

标签: javascript variables if-statement events

我创建了一个名为total的变量和一个if语句来检查total是否高于或等于10然后它写了一些文本但if语句在我更改变量时并不刷新有人告诉我我需要使用事件在那种情况下,但我不知道如何

var price = 5;

var quantity = 0;

var ldiscountrate = 0.05;

var hdiscountrate = 0.1;

var total = 0;

var oldtotal = price * quantity;

if (oldtotal >= 10) {
    discounttotal = total * ldiscountrate;
    document.write("you have a discount total was " + oldtotal + "total after discount " + total);
}

else if (oldtotal >= 15) {
    total = oldtotal * hdiscountrate;
    document.write("you have a discount total was " + oldtotal + "total after discount " + total);
}

else {

     total = oldtotal
    document.write("you don't have a discount the total is " + total + "$");

}
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>Shopping</title>
        <script type="text/javascript" src="JavaScript.js"></script>
    </head>
    <body>
        
        <button type="button" onclick="var quantity+1">Add one item</button>
        <button type="button" onclick="var quantity-1">Remove one item</button>
       
    </body>
</html>

4 个答案:

答案 0 :(得分:0)

你需要创建一个函数并在具有更新值的onclick事件按钮上调用它。像这样:

var price = 5;

var quantity = 0;

var ldiscountrate = 0.05;

var hdiscountrate = 0.1;

var total = 0;

var oldtotal = price * quantity;


function updateQuantity(increasedQuantity){
   quantity = increasedQuantity;
   ldiscountrate = 0.05;
   hdiscountrate = 0.1;
   total = 0;
   oldtotal = price * quantity;

  if (oldtotal >= 10) {
      discounttotal = total * ldiscountrate;
      document.getElementById('result').innerHTML = "you have a discount total was " + oldtotal + "total after discount " + total;
  }

  else if (oldtotal >= 15) {
      total = oldtotal * hdiscountrate;
      document.getElementById('result').innerHTML = "you have a discount total was " + oldtotal + "total after discount " + total;
  }

  else {

       total = oldtotal;
       document.getElementById('result').innerHTML = "you don't have a discount the total is " + total + "$";

  }
}
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>Shopping</title>
        <script type="text/javascript" src="JavaScript.js"></script>
    </head>
    <body>
        
        <button type="button" onclick="updateQuantity(quantity+1)">Add one item</button>
        <button type="button" onclick="updateQuantity(quantity-1)">Remove one item</button>
        <div id="result"></div>
    </body>
</html>

不确定您希望如何显示它,但document.write效果不佳,您必须更改它。

答案 1 :(得分:0)

这将对您有所帮助,不要忘记包含jquery库。 您可以根据需要更改计算, 我按照我的理解做了。

<div >
    <button type="button" onclick="changequantity('add');">Add one item</button>
    <button type="button" onclick="changequantity('remove');">Remove one item</button>
    <input type="hidden" id="quantity" value="0">
    <input type="hidden" id="total" value="0">
</div>

<script>
function changequantity(dothis){
    var price = 5;
    var ldiscountrate = 0.05;
    var hdiscountrate = 0.1;
    var quantity = $('#quantity').val();
    var total = $('#total').val();
    if(dothis=="add"){
        quantity++;
    }
    if(dothis=="remove"){
        quantity--;
    }

    var oldtotal = price * quantity;

    if (oldtotal >= 10) {
        total = oldtotal - (oldtotal * ldiscountrate);
        console.log("you have a discount total was " + oldtotal + " total after discount " + total);
    }else if (oldtotal >= 15) {
        total = oldtotal * hdiscountrate;
        console.log("you have a discount total was " + oldtotal + " total after discount " + total);
    }else{
         total = oldtotal;
        console.log("you don't have a discount the total is " + total + "$");
    }
    $('#quantity').val(quantity);
    $('#total').val(total);
}
</script>

答案 2 :(得分:0)

首先,您必须引用一个函数,而不是在按钮的quantity处理程序中查找onclick变量。原因是onclick需要一个函数,也称为事件处理程序或事件回调。

我们可以创建一个增加addItem()的{​​{1}}函数和一个减少它的quantity函数。然后,我们可以让每个函数调用removeItem()让所有内容都保持最新。请记住,我们应该努力保持我们的职能精益,并遵循单一责任原则。所以你的代码看起来像这样(为了清楚起见,我已将updateQuantity替换为document.write,并将解释如何进一步改进这些代码:

console.log

这里我们做了几件重要的事情。首先,我们将处理逻辑移动到自己的var price = 5; var quantity = 0; var lDiscountRate = 0.05; var hDiscountRate = 0.1; var total = 0; function updateQuantity(){ var oldTotal = price * quantity; var discountTotal = total * lDiscountRate; if (oldTotal >= 10) { console.log("you have a discount total was " + oldTotal + " total after discount " + total); } else if (oldTotal >= 15) { total = oldTotal * hDiscountRate; console.log("you have a discount total was " + oldTotal + " total after discount " + total); } else { total = oldTotal; console.log("you don't have a discount the total is " + total + "$"); } } function addItem() { quantity++; updateQuantity(); } function removeItem() { quantity--; updateQuantity(); } 函数中,每次添加或删除项目时都会运行该函数。这可以确保数据像您所描述的那样保持“刷新”状态。另一个重要的方面是在函数内部移动updateQuantity,以便在每次调用时更新它。我还声明了oldTotal您未声明并且未在您的代码中使用的内容。

现在我们只需将处理函数discountTotaladdItem绑定到DOM(您的按钮)。我们可以将函数的引用传递给removeItem处理程序,或者我们可以使用事件监听器,这是一种更好的做法。事件监听器将监听规定的事件(在这种情况下为onclick,然后在发生这种情况时执行一个函数。我们需要的是为每个按钮添加'click'然后在我们的按钮中查找它们我们将使用id查找每个按钮并将其存储在变量中,然后使用所有html元素都必须添加监听器的document.querySelector()方法。

最后,我还会添加一个空的addEventListener来打印我们的消息。注意,我们应该避免使用<div>而是写入html元素。为此,我们还使用document.write查找要显示结果的元素,然后将字符串添加到document.querySelector()属性。

innerHTML

最后,我们更新您的HTML位以包含每个按钮的var messageDiv = document.querySelector('#results'); var price = 5; var quantity = 0; var lDiscountRate = 0.05; var hDiscountRate = 0.1; var total = 0; function updateQuantity(){ var oldTotal = price * quantity; if (oldTotal >= 10) { var discountTotal = total * lDiscountRate; messageDiv.innerHTML = "you have a discount total was " + oldTotal + " total after discount " + total; } else if (oldTotal >= 15) { total = oldTotal * hDiscountRate; messageDiv.innerHTML = "you have a discount total was " + oldTotal + " total after discount " + total; } else { total = oldTotal; messageDiv.innerHTML = "you don't have a discount the total is " + total + "$"; } } function addItem () { quantity++; updateQuantity(); } function removeItem () { quantity--; updateQuantity(); } var addButton = document.querySelector('#addButton'); var removeButton = document.querySelector('#removeButton'); addButton.addEventListener('click', function () { addItem(); }); removeButton.addEventListener('click', function () { removeItem(); }); id以打印我们的结果。请注意我们不再需要使用div属性。

onclick

以下是适合您的工作示例:http://jsbin.com/rejutudese/edit?html,js,output

答案 3 :(得分:0)

您已在外部JavaScript文件中声明了'quantity'变量,因此您无需再次声明它。如其他人所述,在JavaScript文件中创建一个函数并使用参数调用它。这是一个示例(请注意,我使用div元素来显示结果):

(外部JS文件)

var price = 5;
var quantity = 0;
var ldiscountrate = 0.05;
var hdiscountrate = 0.1;
var total = 0;
var oldtotal = 0;

function recalculate(diff)
{
    var resultElem = null;

    try
    {
        if(quantity==0 && diff<=0)
        {
            //Ignore
            return;
        }
        else
        {

            resultElem =  document.getElementById("theResult");

            quantity+=diff;
            oldtotal = price * quantity;

            if (oldtotal >= 10) 
            {
                    discounttotal = total * ldiscountrate;
                resultElem.innerHTML="you have a discount total was " + oldtotal + " total after discount " + total;
            }
            else if (oldtotal >= 15) 
            {
                    total = oldtotal * hdiscountrate;
                resultElem.innerHTML="you have a discount total was " + oldtotal + " total after discount " + total;
            }
            else 
            {
                total = oldtotal;
                resultElem.innerHTML="you don't have a discount the total is " + total + "$";
            }
        }
    }
    catch(e)
    {
        alert("recalculate Error:  " + e.Message);
    }
    finally
    {

    }

    return;
}

(HTML文件)

<html>
<head>
<title>Sample Answer</title>
<script type="text/javascript" language="javascript" src="JavaScript.js"></script>
</head>
<body>
    <button type="button" onclick="recalculate(1)" >Add one item</button>
    <button type="button" onclick="recalculate(-1)" >Remove one item</button>
    <hr/>
    <div id="theResult"></div>
</body>
</html>