简体   繁体   English

如何将“多次点击计数器”Javascript 功能简化为一个 Javascript function?

[英]How to simplify “multiple click counter” Javascript functions into one Javascript function?

I have multiple buttons and multiple JS functions that show different counter for different buttons.我有多个按钮和多个 JS 函数,它们为不同的按钮显示不同的计数器。 How can I simplify/condense my multiple JS functions into one function that connects each button to its counter?如何将我的多个 JS 函数简化/压缩为一个 function 将每个按钮连接到其计数器?

Here is the workable example for two buttons, two counters and two JS functions.这是两个按钮、两个计数器和两个 JS 函数的可行示例。 Would you please advise how to simplify/condense it?你能告诉我如何简化/浓缩它吗? Many thanks.非常感谢。

TWO JAVASCRIPT FUNCTIONS and STYLE两个 JAVASCRIPT 功能和样式

<!-- JS and Style in head -->
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script>

function clickCounter1() {
  if (typeof(Storage) !== "undefined") {
    if (localStorage.clickcount1) {
      localStorage.clickcount1 = Number(localStorage.clickcount1)+1;
    } else {
      localStorage.clickcount1 = 1;
    }
    document.getElementById("result1").innerHTML = "You have clicked the button " + localStorage.clickcount1 + " time(s).";
  } else {
    document.getElementById("result1").innerHTML = "Sorry, your browser does not support web storage...";
  }
}
</script>
<script>
function clickCounter2() {
  if (typeof(Storage) !== "undefined") {
    if (localStorage.clickcount2) {
      localStorage.clickcount2 = Number(localStorage.clickcount2)+1;
    } else {
      localStorage.clickcount2 = 1;
    }
    document.getElementById("result2").innerHTML = "You have clicked the button " + localStorage.clickcount2 + " time(s).";
  } else {
    document.getElementById("result2").innerHTML = "Sorry, your browser does not support web storage...";
  }
}
</script>
<style>
.button {
  border: none;
  color: white;
  padding: 1px 3px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}

.button1 {background-color: #4CAF50;} /* Green */
.button2 {background-color: #008CBA;} /* Blue */
</style>
</head>
<!-- End of Head -->

TWO HTML BUTTONS:两个 HTML 按钮:

<p><button class="button button1" onclick="clickCounter1()" type="button" background-color="black" color="white">Click it - Button1 <i class="glyphicon glyphicon-thumbs-up" style="font-size:14px;color:white;"></i></button></p>
<div id="result1"></div>

<p><button class="button Button2" onclick="clickCounter2()" type="button" background-color="black" color="white">Click it - button2 <i class="glyphicon glyphicon-thumbs-up" style="font-size:14px;color:white;"></i></button></p>
<div id="result2"></div>

<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).</p>

I have simplified the clickCounter function into one.我已将clickCounter function 简化为一个。

here changing the related property of Storage object depend upon the index of buttons node-list.此处更改Storage object 的相关属性取决于buttons节点列表的索引。

<p>
    <button class="button button1" type="button" background-color="black" color="white">Click
        it - Button1 <i class="glyphicon glyphicon-thumbs-up" style="font-size:14px;color:white;"></i></button>
</p>
<div class="result"></div>

<p>
    <button class="button Button2" type="button" background-color="black" color="white">Click
        it - button2 <i class="glyphicon glyphicon-thumbs-up" style="font-size:14px;color:white;"></i></button>
</p>
<div class="result"></div>

const buttons = document.querySelectorAll('.button');
const results = document.querySelectorAll('.result');

function clickCounter(button, index) {
    const property = "clickcount" + index + 1;
    if (typeof (Storage) !== "undefined") {
        if (localStorage[property]) {
            console.log(localStorage)
            localStorage[property] = Number(localStorage[property]) + 1;
        } else {
            localStorage[property] = 1;
        }
        results[index].innerHTML = "You have clicked the button " + localStorage[property] + " time(s).";
    } else {
        results[index].innerHTML = "Sorry, your browser does not support web storage...";
    }
}

buttons.forEach((button, index) => {
    button.addEventListener('click', function () {
        clickCounter(button, index)
    })
})

Tried to keep your code structure, so I used function parameter and localStorage methods getItem, setItem试图保持你的代码结构,所以我使用function parameter和 localStorage 方法getItem, setItem

// html // html

<p>
      <button
        class="button button1"
        onclick="clickCounter(1)"
        type="button"
        background-color="black"
        color="white"
      >
        Click it - Button1
        <i
          class="glyphicon glyphicon-thumbs-up"
          style="font-size: 14px; color: white;"
        >
        </i>
      </button>
    </p>
    <div id="result1"></div>

    <p>
      <button
        class="button Button2"
        onclick="clickCounter(2)"
        type="button"
        background-color="black"
        color="white"
      >
        Click it - button2
        <i
          class="glyphicon glyphicon-thumbs-up"
          style="font-size: 14px; color: white;"
        >
        </i>
      </button>
    </p>
    <div id="result2"></div>

    <p>Click the button to see the counter increase.</p>
    <p>
      Close the browser tab (or window), and try again, and the counter will
      continue to count (is not reset).
    </p>

// JS // JS

function clickCounter(num) {
  let counterIndex = `clickcount${num}`;
  console.log(counterIndex, localStorage);
  if (typeof Storage !== "undefined") {
    if (localStorage.getItem(`clickcount${num}`)) {
      localStorage.setItem(
        `clickcount${num}`,
        Number(localStorage.getItem(`clickcount${num}`)) + 1
      );
    } else {
      localStorage.setItem(`clickcount${num}`, 1);
    }
    document.getElementById(`result${num}`).innerHTML =
      "You have clicked the button " +
      localStorage.getItem(`clickcount${num}`) +
      " time(s).";
  } else {
    document.getElementById(`result${num}`).innerHTML =
      "Sorry, your browser does not support web storage...";
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM