如何在使用jquery重新加载页面后存储变量

时间:2018-03-30 09:05:28

标签: javascript jquery

我有Prestashop 1.6。我想禁用"添加到购物车"按钮,直到客户点击"保存按钮"。所以他应该在其他领域输入一些描述。

这是我的#34;加入购物车"开头的按钮:

<button type="submit" name="Submit" class="exclusive" disabled="disabled">
    <span>Add to cart</span>
</button>

这部分没问题。现在,我有一个关于这个元素的事件:

<button class="button btn btn-default button button-small" name="saveCustomization">
    <span>Save</span>
</button>

但是当我点击按钮时,我从未进入此功能。 saveButton变量未设置为1.我做错了什么?

我的整个代码:

sessionStorage.setItem("saveButton", 0);

$(document).ready(function () {

    //init process
    $(window).on("load", function () {
        if (sessionStorage.getItem("saveButton") === 1) {
            $('button.exclusive').removeAttr("disabled");
        } else {
            $('button.exclusive').attr("disabled", "disabled");
        }
    });

    $('button[name=saveCustomization]').click(function () {
        saveButton = 1;
        sessionStorage.setItem("saveButton", saveButton);
    });
}); 

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

  1. 您不需要window.load活动,document.ready已足够
  2. 使用== "1"代替===1
  3. 示例:

       $(document).ready(function() {
    
          console.log(sessionStorage.getItem("saveButton"));
    
          //init process    
          if (sessionStorage.getItem("saveButton") == "1") {
            $('button.exclusive').removeAttr("disabled");
          } else {
            $('button.exclusive').attr("disabled", "disabled");
          }
    
          $('button[name=saveCustomization]').click(function() {
            saveButton = 1;
            sessionStorage.setItem("saveButton", saveButton);
          });
        });
    

    看看这个小提琴:https://jsfiddle.net/xpvt214o/8563/

答案 1 :(得分:0)

您的代码中发现了两个问题。

  1. 设置会话存储值后,您不会比较这些值。因为您在window.load()内写了条件。设置新值后,此功能不会触发。
  2. 在会话存储中设置值时,会将其存储为String。现在,您使用===比较值,这意味着类型也应该匹配。但根据你的代码,它永远不会成功。您必须更改sessionStorage.getItem("saveButton") === "1"之类的代码或仅使用==
  3. 所以你必须更新你的代码,如下所示。

    sessionStorage.setItem("saveButton", 0);
    
    $(document).ready(function () {
    
    //init process
    $(window).on("load", function () {
        checkStatus();
    });
    
    $('button[name=saveCustomization]').click(function () {
        alert("came inside");
        saveButton = 1;
        sessionStorage.setItem("saveButton", 1);
        checkStatus();
    });
    function checkStatus() {
      if (sessionStorage.getItem("saveButton") === "1") {
            $('button.exclusive').removeAttr("disabled");
        } else {
            $('button.exclusive').attr("disabled", "disabled");
        }
      }
    }); 
    

    Fiddle Demo