使用不同的存储空间制作2个柜台

时间:2019-01-08 13:16:27

标签: javascript html

我将要做更多的事情,所以只需要有关如何使它们成为不同计数器的帮助,我就厌倦了google和一些html文档,但找不到解决方法。

function clickCounter() {
  if (typeof(Storage) !== "undefined") {
    if (localStorage.clickcount) {
      localStorage.clickcount = Number(localStorage.clickcount) + 1;
    } else {
      localStorage.clickcount = 1;
    }
    document.getElementById("result").innerHTML = "Sälj  " + localStorage.clickcount + "  st.";
  } else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
  }
}

function clickCounter(b) {
  if (typeof(Storage) !== "undefined") {
    if (localStorage.clickcountr) {
      localStorage.clickcountr = Number(localStorage.clickcountr) + 1;
    } else {
      localStorage.clickcountr = 2;
    }
    document.getElementById("resultr").innerHTML = "Annu  " + localStorage.clickcountr + "  st.";
  } else {
    document.getElementById("resultr").innerHTML = "Sorry, your browser does not support web storage...";
  }
}
<p><button onclick="clickCounter()" type="button">Sälj!</button></p>
<div id="result"></div>

<p><button onclick="clickCounter(b)" type="button">Annu!</button></p>
<div id="resultr"></div>

  1. -Sälj=第一个柜台
  2. -Annu =第二个计数器

1 个答案:

答案 0 :(得分:2)

问题在于您以相同的方式命名了函数。因此,第二个函数将覆盖第一个函数,结果两个函数都调用同一个函数。

通常,您不需要编写执行相同操作的两个不同函数。在您的情况下,您的JavaScript函数应如下所示:

function clickCounter(id, label) {
    var node = document.getElementById(id);
    if (!node) {
        return console.error('Element #' + id + ' not found');
    }

    if (window.localStorage === undefined) {
        node.innerHTML = 'Sorry, your browser does not support web storage...';
    } else {
        var key = 'clickcount_' + id;
        localStorage[key] = (++localStorage[key] || 1);
        node.innerHTML = label + ' ' + localStorage[key] + ' st.';
    }
}

以及您的按钮:

<p><button onclick="clickCounter('result', this.innerHTML)" type="button">Sälj!</button></p>
<div id="result"></div>

<p><button onclick="clickCounter('resultr', this.innerHTML)" type="button">Annu!</button></p>
<div id="resultr"></div>