Реализация локального хранилища для хранения данных - PullRequest
0 голосов
/ 05 августа 2020

Я хочу добавить файлы cookie в этот код, но не знаю как. может кто-нибудь помочь? код довольно длинный, так что приготовьтесь.

<html lang="en-us">

<head>
    <meta charset="utf-8">
    <title>Payment</title>
    <link rel="stylesheet" href="Main.css">
<script>
    var Cash = 0
    var Card = 0
    var Amount = 0
    var MPC = 1 //mpc = money per click
    var MPCPrice = 10
    function submit(){
        Amount = document.getElementById("Amount").value;
        document.getElementById("result").textContent = "You spent $" + Amount
            if (Amount == "Infinity"){
                document.getElementById("result").textContent = "uhh i can't let you do that you'll break the website soooooo i reverted your money back to 0. Your welcome."
                Cash = 0
                document.getElementById("Cash").textContent = "You have $" + Cash + " in your bank account"
            else {
                if (Amount < 0) {
                    document.getElementById("result").textContent = "Transaction failed; you used a negative number you cheater, you are not getting any money."
                    document.getElementById("Cash").textContent = "You have $" + Cash + " in your bank account"
                }
                else {
                    if (Amount == ""){
                        document.getElementById("result").textContent = "Transaction failed; you typed nothing in, i mean what did you expect to happen?"
                    }
                    else {
                            if (Cash >= Amount){
                                        Cash = Cash - Amount
            document.getElementById("Cash").textContent = "You have $" + Cash + " in your bank account"
        }
        else {
            document.getElementById("result").textContent = "Transaction invalid; you do not have enough money."
        }
                        }
                        

                    }
                    
                }

            }

        }
        

    function text(){
      Cash = Cash + MPC //max and min in that order
      document.getElementById("Cash").textContent = "You have $" + Cash + " in your bank account"
    }
    
    function MPCUpgrade(){
      if (Cash >= MPCPrice){
        MPC = MPC + 2
        Cash = Cash - MPCPrice
        MPCPrice = MPCPrice * 2
        document.getElementById("Cash").textContent = "You have $" + Cash + " in your bank account"
        document.getElementById("MPC").textContent = "You're money per click is $" + MPC + ". It costs $" + MPCPrice + " to upgrade it."
      }
    }
    
    function start() {
        document.getElementById("Cash").textContent = "You have $" + Cash + " in your bank account"
        document.getElementById("MPC").textContent = "You're money per click is $" + MPC + ". It costs $" + MPCPrice + " to upgrade it."
        document.getElementById("Cash").textContent = "You have $" + Cash + " in your bank account"
    }
</script>
</head>

<body onload="start()">
    <center>
    <h1>Payment</h1>
    <div id="Cash"></div>
    <h2>Amount</h2>
    <input id="Amount" class="text" type="text"><br>
    <h2>Card Number</h2>
    <input id="Card" class="text" type="text"><br>
    <br>
    <button class="button-long" onclick="submit()">Done</button>
    <div id="result"></div>
    <div id="show1"></div>
    <h1>Get Money</h1>
    <button class="button-long" onclick="text()">Get Money</button>
    <h1>Upgrades</h1>
    <button id="Upgrade1" class="button-longer" onclick="MPCUpgrade()">Money per click Upgrade</button><br>
    <div class="text" id="MPC"></div><br>
    <div class="text" id="MPCPrice"></div>
</center>
</body>

</html>

Я хочу сэкономить около sh и сколько денег вы получаете за клик. карту и сумму копить не нужно. Я попытался сделать файлы cookie и прочитать кучу stackoverflow, но ничего не нашел. когда я попытался добавить его, он просто сказал бы null или просто добавил бы к нему больше единицы вместо увеличения суммы ca sh.

1 Ответ

0 голосов
/ 05 августа 2020

Вы можете добавить в свой проект локальное хранилище и включить несколько функций для сохранения и извлечения данных.

    <html lang="en-us">
  <head>
    <meta charset="utf-8" />
    <title>Payment</title>
    <!-- <link rel="stylesheet" href="Main.css" /> -->
  </head>

  <body>
    <center>
      <h1>Payment</h1>
      <div id="Cash"></div>
      <h2>Amount</h2>
      <input id="Amount" class="text" type="text" /><br />
      <h2>Card Number</h2>
      <input id="Card" class="text" type="text" /><br />
      <br />
      <button class="button-long">Done</button>
      <div id="result"></div>
      <div id="show1"></div>
      <h1>Get Money</h1>
      <button class="button-long">Get Money</button>
      <h1>Upgrades</h1>
      <button id="Upgrade1" class="button-longer">
        Money per click Upgrade</button
      ><br />
      <div class="text" id="MPC"></div>
      <br />
      <div class="text" id="MPCPrice"></div>

      <button class="delete-button">Clear Memory</button>
    </center>
  </body>
  <script>
    (function () {
      const $doneButton = document.querySelector('.button-long');
      const $getMoneyButton = document.querySelectorAll('.button-long')[1];
      const $moneyPerClickButton = document.querySelector('.button-longer');
      const $deleteButton = document.querySelector('.delete-button');

      const LOCALSTORAGE_KEY = 'money-project';

      let moneyInformation = {};

      //   let Cash = moneyInformation.cash;
      //   let Card = moneyInformation.card;
      //   let Amount = moneyInformation.amount;
      // let MPC = 1; //mpc = money per click
      // let MPCPrice = 10;

      function submit() {
        moneyInformation.amount = document.getElementById('Amount').value;
        document.getElementById('result').textContent =
          'You spent $' + moneyInformation.amount;
        if (moneyInformation.amount == 'Infinity') {
          document.getElementById('result').textContent =
            "uhh i can't let you do that you'll break the website soooooo i reverted your money back to 0. Your welcome.";
          moneyInformation.cash = 0;
          document.getElementById('Cash').textContent =
            'You have $' + moneyInformation.cash + ' in your bank account';
          saveData();
        } else {
          if (moneyInformation.amount < 0) {
            document.getElementById('result').textContent =
              'Transaction failed; you used a negative number you cheater, you are not getting any money.';
            document.getElementById('Cash').textContent =
              'You have $' + moneyInformation.cash + ' in your bank account';
          } else {
            if (moneyInformation.amount == '') {
              document.getElementById('result').textContent =
                'Transaction failed; you typed nothing in, i mean what did you expect to happen?';
            } else {
              if (moneyInformation.cash >= moneyInformation.amount) {
                moneyInformation.cash =
                  moneyInformation.cash - moneyInformation.amount;
                document.getElementById('Cash').textContent =
                  'You have $' +
                  moneyInformation.cash +
                  ' in your bank account';
                saveData();
              } else {
                document.getElementById('result').textContent =
                  'Transaction invalid; you do not have enough money.';
              }
            }
          }
        }
      }

      function text() {
        moneyInformation.cash = moneyInformation.cash + moneyInformation.MPC; //max and min in that order
        document.getElementById('Cash').textContent =
          'You have $' + moneyInformation.cash + ' in your bank account';
        saveData();
      }

      function MPCUpgrade() {
        if (moneyInformation.cash >= moneyInformation.MPCPrice) {
          moneyInformation.MPC = moneyInformation.MPC + 2;
          moneyInformation.cash =
            moneyInformation.cash - moneyInformation.MPCPrice;
          moneyInformation.MPCPrice = moneyInformation.MPCPrice * 2;

          console.log(moneyInformation);
          document.getElementById('Cash').textContent =
            'You have $' + moneyInformation.cash + ' in your bank account';
          document.getElementById('MPC').textContent =
            "You're money per click is $" +
            moneyInformation.MPC +
            '. It costs $' +
            moneyInformation.MPCPrice +
            ' to upgrade it.';
          saveData();
        }
      }

      function setUpListeners() {
        $doneButton.addEventListener('click', submit);
        $getMoneyButton.addEventListener('click', text);
        $moneyPerClickButton.addEventListener('click', MPCUpgrade);
        $deleteButton.addEventListener('click', clearMemory);
      }

      function saveData() {
        window.localStorage.setItem(
          LOCALSTORAGE_KEY,
          JSON.stringify(moneyInformation)
        );
      }

      function retrieveData() {
        try {
          moneyInformation = JSON.parse(
            window.localStorage.getItem(LOCALSTORAGE_KEY)
          ) || { cash: 0, card: 0, amount: 0, MPC: 1, MPCPrice: 10 };
          console.log(moneyInformation);
        } catch (e) {
          console.log('not json value');
        }
      }

      function clearMemory() {
        window.localStorage.clear();
        retrieveData();
        renderText();
      }

      function renderText() {
        document.getElementById('Cash').textContent =
          'You have $' + moneyInformation.cash + ' in your bank account';
        document.getElementById('MPC').textContent =
          "You're money per click is $" +
          moneyInformation.MPC +
          '. It costs $' +
          moneyInformation.MPCPrice +
          ' to upgrade it.';
        document.getElementById('Cash').textContent =
          'You have $' + moneyInformation.cash + ' in your bank account';
      }

      function init() {
        setUpListeners();
        retrieveData();
        renderText();
      }
      init();
    })();
  </script>
</html>

Просто используйте retrieveData при загрузке проекта, а затем вызовите saveData, когда вы хотите сохранить информация.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...