Home > Software design >  JavaScript function about local storage
JavaScript function about local storage

Time:03-22

I have an UI with 4 navigation: Home, Page 1, Page 2, Page 3

<ul >
  <li >
    <a  href="#">Home</a>
  </li>
  <li >
    <a  onclick="visitLink('Page1')" href="page_1.html">Page 1</a>
  </li>
  <li >
    <a  onclick="visitLink('Page2')" href="page_2.html">Page 2</a>
  </li>
  <li >
    <a  onclick="visitLink('Page3')" href="page_3.html">Page 3</a>
  </li>
</ul>

<button type="button" onclick="viewResults()" 
        >
  View page visits results
</button>

And a function increasing the times we click 3 navs Page 1, Page 2, Page 3 seperated (I use path is a key, and the times is value):

function visitLink(path) {
    
    if (localStorage.getItem(path) === null) {
        // Store
        localStorage.setItem(path, "0");
    }
    localStorage.setItem(path, parseInt(localStorage.getItem(path))   1);
    return localStorage.getItem(path);
}

The function to display the result of each clicks in each page (it's not completed, I used this to debug):

function viewResults() {
  alert("You visited Page time(s) "   visitLink('Page1'))
}

But when I saw the result, it increased the result by 2, not 1 if I click Home button (count as 1 time of clicking) to return to see the result. How can I fix that?

CodePudding user response:

The result is two because you are calling visitLink to retrieve the count, which also increments the count.

Given that you must implement the task with two functions, I would suggest adding another parameter to the visitLink function which indicates whether the count should be incremented:

function visitLink(path, readonly) {
  if (localStorage.getItem(path) === null) {
    localStorage.setItem(path, "0");
  }
  if(!readonly){
    localStorage.setItem(path, parseInt(localStorage.getItem(path))   1);
  }
  return localStorage.getItem(path);
}

function viewResults() {
  alert("You visited Page time(s) "   visitLink('Page1', true))
}

CodePudding user response:

You are calling the function that increases the counter here alert("You visited Page time(s) " visitLink('Page1')), when calling visitLink('Page1')you fetch the result but also increase it

This should fix it, although I would recommend a getResult function

alert("You visited Page time(s) "   localStorage.getItem('Page1'))
  • Related