jQuery 按钮在值更改后首次单击时不起作用

jQuery button doesnt work on first click after value change

本文关键字:单击 不起作用 按钮 jQuery      更新时间:2023-09-26

所以,我正在检查localStorage以查看某些键是否存在,如果是,那么我更改按钮值。

$(document).ready(function() {
    console.log(localStorage.length);
    ProductName = $("#ProductNameHidden").text();
    for (var i = 0; i < localStorage.length; i++) {
        if (localStorage.key(i) == ProductName) {
            document.getElementById("SubmitButton").value = "GO TO CART";
            return false;
        } else {
            document.getElementById("SubmitButton").value = "ADD TO CART";
        }
    }
});
当我点击按钮时,

第一次什么也没发生,只有当我第二次点击它时。

if (document.getElementById("SubmitButton").value == "GO TO CART") {
    $("#SubmitButton").click(function() {
        window.location.href = "Cart.html"
    });
}

应该是,

$("#SubmitButton").click(function() {
  if ($(this).val() == "GO TO CART") {
    window.location.href = "Cart.html"
  }
});