為什么遞增和遞減按鈕不工作,他們工作得很好,但當我添加類型= & quot按鈕& quot停止工作。
超文本標記語言
<form th:action="@{/home}" method="post" style="margin-top: 10px; display: block">
<div style="margin-bottom: 10px; margin-top: 10px;">
<button type="button" name="decrement" onclick="decrement()" style="display: inline; margin-right: 5px; width: 20px" id="decrement">-</button>
<output style="display: inline" name="quantity" id="quantity">0</output>
<button type="button" name="increment" onclick="increment()" style="display: inline; margin-left: 5px; width: 20px" id="increment">+</button>
<input type="hidden" name="itemId" th:value="${item.getItem_id()}"/>
<button type="submit" name="addToCart" class="addToCart-btn">Add to cart</button>
</div>
</form>
java描述語言
function increment(button) {
var counter = button.parentNode.querySelector("output");
counter.textContent++;
updateAddToCartButton(button)
}
function decrement(button) {
var counter = button.parentNode.querySelector("output");
if (counter.textContent > 0) {
counter.textContent--;
updateAddToCartButton(button)
}
}
function updateAddToCartButton(button) {
var quantity = parseInt(button.parentNode.querySelector("#quantity").innerText);
var submitButton = button.parentNode.querySelector(".addToCart-btn");
if (quantity > 0) {
submitButton.style.display = "inline";
} else {
submitButton.style.display = "none";
}
}
主要問題是您正在使用內聯事件處理程序。在這個上下文中,increment指的是具有increment id的按鈕,而不是函數。您也沒有向increment和decrement傳遞任何參數,因此按鈕在兩者中都是未定義的。
請改用帶有event.target的addEventListener。
document.querySelector('#increment').addEventListener('click', e => increment(e.target));
document.querySelector('#decrement').addEventListener('click', e => decrement(e.target));
function increment(button) {
var counter = button.parentNode.querySelector("output");
counter.textContent++;
updateAddToCartButton(button)
}
function decrement(button) {
var counter = button.parentNode.querySelector("output");
if (counter.textContent > 0) {
counter.textContent--;
updateAddToCartButton(button)
}
}
function updateAddToCartButton(button) {
var quantity = parseInt(button.parentNode.querySelector("#quantity").innerText);
var submitButton = button.parentNode.querySelector(".addToCart-btn");
if (quantity > 0) {
submitButton.style.display = "inline";
} else {
submitButton.style.display = "none";
}
}
<form th:action="@{/home}" method="post" style="margin-top: 10px; display: block">
<div style="margin-bottom: 10px; margin-top: 10px;">
<button type="button" name="decrement" style="display: inline; margin-right: 5px; width: 20px" id="decrement">-</button>
<output style="display: inline" name="quantity" id="quantity">0</output>
<button type="button" name="increment" style="display: inline; margin-left: 5px; width: 20px" id="increment">+</button>
<input type="hidden" name="itemId" th:value="${item.getItem_id()}"/>
<button type="submit" name="addToCart" class="addToCart-btn">Add to cart</button>
</div>
</form>