温馨提示:本文翻译自stackoverflow.com,查看原文请点击:Javascript implementation of arrows in input numbe - How to make so that changes concerned each item?
javascript

Javascript implementation of arrows in input numbe - 如何使变更涉及每个项目?

发布于 2020-03-27 12:03:13

我有一篮子商品,其中可以有许多不同的实体。我正在尝试使用input - number无箭头和附加按钮来实现商品数量的更改+/-我知道我可以使用identifiers并轻松制定计划。但就我而言,我需要使用querySelectorAll帮助我,请更正此代码。quantity-arrow-minus减小字段值并quantity-arrow-plus增加。如何使更改与每个项目相关?

var minus = document.querySelectorAll('.quantity-arrow-minus');
var update_cart = document.querySelectorAll('.update_cart');
var plus = document.querySelectorAll('.quantity-arrow-plus');

minus.forEach(function(node) {
node.addEventListener('click', function() {
    update_cart.forEach(function(element) {
        element.value = parseInt(element.value) - 1;
    });
});
});

plus.forEach(function(node) {
node.addEventListener('click', function() {
    update_cart.forEach(function(element) {
        element.value = parseInt(element.value) + 1;
    });
});
});
<form method="GET">
<button type="button" class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button type="button" class="quantity-arrow-plus">+</button>
</form>

<form method="GET">
<button type="button" class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button type="button" class="quantity-arrow-plus">+</button>
</form>

查看更多

查看更多

提问者
karaname
被浏览
20
antonku 2019-07-03 23:48

您可以使用previousElementSibling和nextElementSibling访问与单击的按钮相对应的输入:

var minus = document.querySelectorAll('.quantity-arrow-minus');
var update_cart = document.querySelectorAll('.update_cart');
var plus = document.querySelectorAll('.quantity-arrow-plus');

minus.forEach(function(node) {
    node.addEventListener('click', function(e) {
       const input = e.target.nextElementSibling
       input.value = parseInt(input.value) - 1;
    });
});

plus.forEach(function(node) {
    node.addEventListener('click', function(e) {
       const input = e.target.previousElementSibling
       input.value = parseInt(input.value) + 1;
    });
});
<form action="{% url 'cart:cart_update' %}" method="GET">
    <button type="button" class="quantity-arrow-minus">-</button>
    <input type="number" class="update_cart" value="0">
    <button type="button" class="quantity-arrow-plus">+</button>
    <br>
    <button type="button" class="quantity-arrow-minus">-</button>
    <input type="number" class="update_cart" value="0">
    <button type="button" class="quantity-arrow-plus">+</button>
</form>