1

我正在尝试创建增加或减少数量值的按钮。

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

2 回答 2

4

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

于 2013-02-07T22:07:36.123 回答
2

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

jFiddle在这里

于 2013-02-07T22:16:48.810 回答