0

您好,我对此很陌生,我正在尝试使此运输计算器代码正常工作。这就是我到目前为止所拥有的。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
ent"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Calculate Shipping</title>
<script type="text/javascript">
/* <![CDATA[ */
var price = 0;
var shipping = (calculateShipping(price););
var total = price + shipping;

function calculateShipping(price){
    if (price <= 25){
        return 1.5;
    }
    else {
        return price * 10 / 100;
        break;
    } 
}

window.alert("Your total is $" + total + ".");

/* ]]> */
</script>
</head>
<body>
<form name="shipping" action="">
    <p>Purchase Price: $
        <input type="text" name="price" />
        <input type="button" value="Calculate Shipping" onclick="calculateshipping(price);" />
    </p>
</form>
</body>
</html>
4

2 回答 2

1

将您的 onclick 代码更改为:

calculateShipping(document.getElementById('price').value);

编辑,试试这段代码,它应该可以工作:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"       ent"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Calculate Shipping</title>

<script type="text/javascript">
/* <![CDATA[ */
var price = 0;
var shipping = calculateShipping(price);

function calculateShipping(price){
var result = 0;
if (price <= 25){
    result = 1.5;
}
else{
    result = price * 10 / 100;
}
var total = result + (price - 0);
window.alert("Shipping is $" + result + ".  Total is $" + total +".");
} 

/* ]]> */
</script>
</head>
<body>
<p>Purchase Price: $
<input type="text" name="price" id="price" />
<input type="button" value="Calculate Shipping" onclick="calculateShipping(document.getElementById('price').value);" /></p>
</body>
</html>
于 2012-09-30T03:42:54.020 回答
1

我认为最好的方法(不使用任何库,如 JQuery)如下:

<!DOCTYPE html>
<html>
<head>
<title>Calculate Shipping</title>
<script type="text/javascript">

window.addEventListener('load', function(){
  var priceField = document.getElementById('price');
  var calculateButton = document.getElementById('calculate');
  var totalField = document.getElementById('total');

  calculateButton.addEventListener('click', function(){
    var price = parseInt(priceField.value);
    var shipping = calculateShipping(price);
    var total = price + shipping;

    totalField.value = "Your total is $" + total + ".";
  });

  function calculateShipping(price){
    return (price <= 25) ? 1.5 : price / 10;
  }
});


</script>
</head>
<body>

<h1>Purchase Price:</h1>

<label>Price:</label><input type="text" id="price" />
<button id="calculate">Calculate Shipping</button>

<label>Total:</label>
<input type="text" id="total" disabled="disabled" />

</body>
</html>

这里我介绍一些好的做法,比如:

  • 不要污染全局命名空间
  • 避免内联 Javascript(将事件侦听器绑定为 HTML 属性)
  • 如果可能,请避免使用本机消息框(警报、确认、提示...),它们非常具有侵入性、丑陋且不可定制。
于 2012-09-30T04:31:13.973 回答