JavaScript 在指定条件下阻止按钮事件

JavaScript prevent button event on specified conditions

我有一个类似网上商店的购物车功能。它显示为您添加的产品。您可以通过单击 +- 按钮来更改产品数量。 单击按钮时,AJAX 调用将发送到更新数据库的 PHP 文件,以便您立即保存实际数量。 当您增加或减少所选数量时,会出现一个计数器,指示原始产品将乘以多少次。您可以在 1 and 30 之间增加或减少数量。例如,当您到达 1 时,计数器停止,但是 AJAX 呼叫将被发送,无论它不应该低于 1。

Preview video

let subt = 30; // The value from PHP after you sent the AJAX call and reloaded the page
document.getElementById("plus").addEventListener("click", () => {
  if (document.getElementById("inp").value < 30) {
    document.getElementById("inp").value = Number(document.getElementById("inp").value) + 1;
  }
  if (document.getElementById("inp").value > 1) {
    /*
        var bsi__data = new FormData(); bsi__data.append("pid", '(product id)'); bsi__data.append("quantity", document.getElementById("inp").value); bsi__data.append("price", "30");
        $.ajax({
            enctype: "multipart/form-data", type: "POST", url: "/assets/php/basket/q__up.php", data: bsi__data, dataType: "json", contentType: false, processData: false,
            success: function(data) { console.log(data); subt += Number('30'); document.getElementById("subtotal").textContent = formatter.format(subt); },
            error: function (data) { console.log("error"); console.log(data); }
        });
        */
    subt += Number('30');
    document.getElementById("subtotal").textContent = subt;
    document.getElementById("ind").textContent = "x " + document.getElementById("inp").value;
  }
  if (document.getElementById("inp").value == 1) {
    document.getElementById("ind").textContent = "";
  }
});
document.getElementById("min").addEventListener("click", function dicr() {
  if (document.getElementById("inp").value > 1) {
    document.getElementById("inp").value = Number(document.getElementById("inp").value) - 1;
  }
  if (document.getElementById("inp").value >= 1) {
    /*
    var bsi__data = new FormData(); bsi__data.append("pid", "(product id)"); bsi__data.append("quantity", document.getElementById("inp").value);
    $.ajax({
        enctype: "multipart/form-data", type: "POST", url: "/assets/php/basket/q__up.php", data: bsi__data, dataType: "json", contentType: false, processData: false,
        success: function(data) { console.log("decr"); subt -= Number(30); document.getElementById("subtotal").textContent = formatter.format(subt); },
        error: function (data) { console.log("error"); console.log(data); }
    });
    */

    subt -= Number(30);
    document.getElementById("subtotal").textContent = subt;
    document.getElementById("ind").textContent = "x " + document.getElementById("inp").value;
  }
  if (document.getElementById("inp").value == 1) {
    document.getElementById("ind").textContent = "";
  }
});
<div>
  <span>Product name</span><span id="price"></span><span id="ind"></span>
  <div>
    <span id="plus">+</span>
    <input type="number" id="inp" min="1" max="30" value="1" />
    <span id="min">-</span><br><br>
    <span>Subtotal: $</span>
    <span id="subtotal">30</span>
  </div>
</div>

https://jsfiddle.net/jnerx76z/

document.getElementById("plus").addEventListener("click", () => {
  if (document.getElementById("inp").value < 30) {
    document.getElementById("inp").value = Number(document.getElementById("inp").value) + 1;
  }
  if (document.getElementById("inp").value > 1) {
    /*
        var bsi__data = new FormData(); bsi__data.append("pid", '(product id)'); bsi__data.append("quantity", document.getElementById("inp").value); bsi__data.append("price", "30");
        $.ajax({
            enctype: "multipart/form-data", type: "POST", url: "/assets/php/basket/q__up.php", data: bsi__data, dataType: "json", contentType: false, processData: false,
            success: function(data) { console.log(data); subt += Number('30'); document.getElementById("subtotal").textContent = formatter.format(subt); },
            error: function (data) { console.log("error"); console.log(data); }
        });
        */
    subt += Number('30');
    document.getElementById("subtotal").textContent = subt;
    document.getElementById("ind").textContent = "x " + document.getElementById("inp").value;
  }
  if (document.getElementById("inp").value == 1) {
    document.getElementById("ind").textContent = "";
  }
});
document.getElementById("min").addEventListener("click", function dicr() {
    var newValue;
  if (document.getElementById("inp").value > 1) {
    newValue = Number(document.getElementById("inp").value) - 1;
    document.getElementById("inp").value = newValue;
  }
  if (newValue >= 1) {
  alert(newValue)
    /*
    var bsi__data = new FormData(); bsi__data.append("pid", "(product id)"); bsi__data.append("quantity", document.getElementById("inp").value);
    $.ajax({
        enctype: "multipart/form-data", type: "POST", url: "/assets/php/basket/q__up.php", data: bsi__data, dataType: "json", contentType: false, processData: false,
        success: function(data) { console.log("decr"); subt -= Number(30); document.getElementById("subtotal").textContent = formatter.format(subt); },
        error: function (data) { console.log("error"); console.log(data); }
    });
    */

    subt -= Number(30);
    document.getElementById("subtotal").textContent = subt;
    document.getElementById("ind").textContent = "x " + document.getElementById("inp").value;
  }
  if (document.getElementById("inp").value == 1) {
    document.getElementById("ind").textContent = "";
  }
});

完成所需操作的简单方法是使用 Math.min()Math.max() 设置字段的允许范围。然后您修改逻辑以根据该字段更新时的值计算小计,而不是通过维护全局变量。

另请注意,您应该将您在代码中经常引用的 Element 对象放入变量中。这使您的代码更短且更易于阅读,并且性能更高,因为访问 DOM 是一个相对较慢的操作,应尽可能避免。

话虽如此,这里有一个工作示例:

let inp = document.querySelector('#inp');
let ind = document.querySelector('#ind');
let subtotal = document.querySelector('#subtotal');
let minQty = 0;
let maxQty = 30;
let itemCost = 30;

document.querySelector("#plus").addEventListener("click", () => {
  inp.value = Math.min(maxQty, Math.max(minQty, +inp.value + 1));
  updateSubtotalUI();
});

document.getElementById("min").addEventListener("click", function dicr() {
  inp.value = Math.min(maxQty, Math.max(minQty, +inp.value - 1));
  updateSubtotalUI();
});

let updateSubtotalUI = () => {
  let subt = inp.value * itemCost;
  subtotal.textContent = subt.toLocaleString();
}
<div>
  <span>Product name</span>
  <span id="price"></span>
  <span id="ind"></span>
  <div>
    <span id="plus">+</span>
    <input type="number" id="inp" min="1" max="30" value="1" />
    <span id="min">-</span><br><br>
    <span>Subtotal: $</span>
    <span id="subtotal">30</span>
  </div>
</div>