【发布时间】:2017-08-06 23:05:18
【问题描述】:
我正在尝试开发一个网页来计算折扣价格并显示在网页本身上。主要是用相同的onclick 事件触发这两个函数,但它不会运行,就我是初学者而言,我不知道这些函数是写错了还是其他的。我需要在一个id="discount" 中显示折扣百分比,在另一个id="result" 中显示折扣价格。无法弄清楚我在哪里搞砸了,任何帮助将不胜感激。
function calculate() {
var product_name = document.getElementById('name').value;
var product_price = document.getElementById('price').value;
var select = document.getElementById("sale");
var selected = select.options[select.selectedIndex].value;
if (selected == summer) {
var discount_price = product_price - (product_price * 0.10);
} else if (selected == newyear) {
var discount_price = product_price - (product_price * 0.05);
} else {
var discount_price = product_price - (product_price * 0.15);
}
// body...
}
function display_sale() {
if (selected == summer) {
document.getElementById('discount').innerHTML = "The discount is 10%";
} else if (selected == newyear) {
document.getElementById('discount').innerHTML = "The discount is 5%";
} else {
document.getElementById('discount').innerHTML = "The discount is 15%";
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="container">
<form>
<h1>DISCOUNT PRICE</h1>
<table>
<tr>
<td>Product Name</td>
<td colspan="2"><input type="text" name="name" id="name" pattern="[a-zA-Z\s]+" required="required"></td>
</tr>
<tr>
<td>Product Price</td>
<td colspan="2"><input type="text" name="price" id="price" pattern="([1-9][0-9]*(\.[0-9]*[1-9])?|0\.[0-9]*[1-9])" required="required"></td>
</tr>
<tr>
<td>Season</td>
<td colspan="2"><select id="sale">
<option value="summer">SUMMER SALE</option>
<option value="newyear">NEW YEAR SALE</option>
<option value="clearance">CLEARANCE SALE</option>
</select>
</td>
</tr>
</table><br/>
<div style="margin-left: 40%">
<button type="submit" onclick="calculate();"> GET DISCOUNT PRICE</button>
</div>
<div id="discount">
</div>
<div id="result">
</div>
</div>
</form>
</body>
</html>
【问题讨论】:
-
单击按钮,检查开发人员工具控制台 - 看到错误
ReferenceError: selected is not defined- 这是因为您使用了未定义的变量selected。提示:summer和newyear也没有定义 -
我已经在脚本中定义了它,那不行吗?如果我使用 var 定义,或者我应该将值放在“”中?
-
可能在
calculate中,但不在display_sale中,它首先被调用,无论如何,claculate中的定义无论如何都不能在 display_sale 中使用 -
javascript 执行但突然消失 @JaromandaX
-
是的,当你提交表单时,页面在浏览器中被替换
标签: javascript html dom dom-events