2013-02-07 64 views
0

我试图创建增加或减少数量值的按钮。HTML/JavaScript - 数量不起作用的向上和向下按钮

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;} 
} 

这是很添油加醋。该功能根据点击哪个按钮而向上或向下传递,然后根据数量元素的当前值确定要执行的操作。不幸的是,它没有做一件事,我不明白为什么。任何帮助将非常感激。

+4

我们可以看到一个[小提琴](http://jsfiddle.net)? – Mooseman

+0

它适用于我 – edi9999

回答

4

我继续前进,并将代码粘贴到小提琴中,并得到控制台错误,在onclick时,setQuantity未定义。确保之前调用它的标记解决了这个问题对我来说,函数声明: http://jsfiddle.net/KR2Az/

+0

是的,就是这样!我应该比这更清楚。感谢您的帮助,也感谢提醒我,小提琴存在。 –

1

正如crowjonah提到,你的JavaScript应该理想地出现在页面的<HEAD>

我也建议您从HTML分离的JavaScript这样的:

<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> 

jFiddle here

相关问题