所以我试图根据选择值更改变量并在更改时显示它。我已经通过以静态方式设置变量来使其正常工作但我不了解如果更改或增加选择值如何更改变量。
在这种情况下,我试图根据数量更改价格。如果数量超过X,则价格会变为Y.请记住我是javascript的新手,所以请保持基本的答案。
这是我目前的代码:
HTML
<label>Single User</label>
<select class="input-mini" name="singleuser" id="singleuser" onchange="changed(this, 0, 34.95)">
<option value="0">0</option>
<option value="1">1</option>
</select> <font size="4"><b>@ $34.95/mo</b></font>
的Javascript
var size = 36;
var cart = new Array();
for (var j = 0; j < size; j++) //initialize cart to all 0
cart[j] = 0;
function changed(me, id, price) {
var amount = me.options[me.selectedIndex].value; //quantity passed
var t_price = amount * price; //multiply operation
cart[id] = t_price; //update cart array
update_spans();
document.getElementById(id).value = amount; //update quantity for final page
}
function update_spans() {
put("cart0", cart[0]);
}
function put(name, price) {
try {
price = (Math.round(price * 100) / 100); //round
price = price.toFixed(2); //two decimal places
document.getElementById(name).innerHTML = price; //put into span
} catch (err) {
//error
}
}
答案 0 :(得分:1)
使用以下代码更改您的HTML和JavaScript部分
// HTML
<label>Single User</label>
<select class="input-mini" name="singleuser" id="singleuser" onchange="changed(this, 0, 34.95)">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<span id="price">@ $34.95/mo</span>
// JavaScript (this is all you need)
var size = 36, cart = [];
var discount = [0, 5, 10, 15, 20, 25, 50];
for(var j = 0; j < size; j++) cart[j] = 0;
function changed(me, id, price){
var amount = me.options[me.selectedIndex].value;
var p_discount = amount * price * (discount[me.selectedIndex]/100);
var t_price = (amount * price) - p_discount;
cart[id] = t_price;
r_price = (Math.round(t_price*100)/100);
r_price = r_price.toFixed(2);
document.getElementById('price').innerHTML = '@ ' + r_price + '/mo';
}
检查工作jsBin