我正在尝试创建增加或减少数量值的按钮。
HTML:
<div class="order-option">
Quantity:
<span id="quantity-field">
<button id="up" onclick="setQuantity('up');">+</button>
<input type="text" id="quantity" value="1">
<button id="down" onclick="setQuantity('down');">-</button>
</span>
</div>
JavaScript的:
function setQuantity(upordown) {
var quantity = document.getElementById('quantity');
if (quantity.value > 1) {
if (upordown == 'up'){++document.getElementById('quantity').value;}
else if (upordown == 'down'){--document.getElementById('quantity').value;}}
else if (quantity.value == 1) {
if (upordown == 'up'){++document.getElementById('quantity').value;}}
else
{document.getElementById('quantity').value=1;}
}
它很干爽。根据单击的按钮,该函数将“向上”或“向下”传递,然后根据数量元素的当前值决定要执行的操作。不幸的是,它没有做任何事情,我无法弄清楚为什么。任何帮助将不胜感激。
答案 0 :(得分:4)
我继续将代码粘贴到一个小提琴中,并得到控制台错误,在onclick时,setQuantity
未定义。确保在调用它的标记之前声明该函数为我解决了问题:
http://jsfiddle.net/KR2Az/
答案 1 :(得分:1)
正如crowjonah所提到的,您的javascript理想情况下应该出现在页面的<HEAD>
中。
我还建议将javascript与HTML分开,如下所示:
<script>
quantity = document.getElementById('quantity');
button_up=document.getElementById('up');
button_down=document.getElementById('down');
button_up.onclick=function() {setQuantity('up');}
button_down.onclick=function() {setQuantity('down');}
function setQuantity(upordown) {
var quantity = document.getElementById('quantity');
if (quantity.value > 1) {
if (upordown == 'up'){++quantity.value;}
else if (upordown == 'down'){--quantity.value;}}
else if (quantity.value == 1) {
if (upordown == 'up'){++quantity.value;}}
else
{quantity.value=1;}
}
</script>
<div class="order-option">
Quantity:
<span id="quantity-field">
<button id="up">+</button>
<input type="text" id="quantity" value="1">
<button id="down">-</button>
</span>
</div>