【问题标题】:Local storage and window.location.href.replace本地存储和 window.location.href.replace
【发布时间】:2021-11-20 07:41:39
【问题描述】:

我和我的同学正在尝试编写一个代码,当单击订单按钮时​​,它应该保存在本地存储中并重定向到订单页面。

到目前为止,当我们点击订单时,它还没有在谷歌开发者工具的应用程序/本地存储部分注册,因此不会重定向到新页面。

我们放置了一个事件监听器来在我们点击时显示一个控制台日志,只是为了确保按钮是按顺序排列的(这部分并不重要)。

我们还使用了在线 javascript 验证器来消除拼写错误。

我们还需要 order.html 文件中的任何特定代码来与本地存储接口吗?

  <!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title>grc</title>
  <link rel="stylesheet" href="css/style.css" type="text/css">
</head>

<body>
  <header>
    <nav>
      <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="groceries.html">Groceries</a></li>
        <li><a href="contact.html">Contact</a></li>
      </ul>
    </nav>
  </header>
  <main>
    <aside><img class="imgclass1" src="images/rounded logo.png" alt="Grocer Nigeria"></aside>
    <article class="preinventory">
      <section class="columns-desktop">
        <div class="inventory">
          <img class="sales" src="images/tomato.jpg" alt="Tomato"/>
          <div class="columns">
            <div class="title">Tomato</div>
            <div class="Price">$100</div>
          </div>
          <p class="Desc"> Our Tomato2</p>
          <button data-order="Tomato2">Order</button>
        </div>

        <div class="inventory">
          <img class="sales" src="images/tomato.jpg" alt="Tomato"/>
          <div class="columns">
            <div class="title">Tomato</div>
            <div class="Price">$100</div>
          </div>
          <p class="desc"> Our Tomato</p>
          <button data-order="Tomato">Order</button>
        </div>
      </section>
    </article>
  </main>
  <footer>
    <nav>
      <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="groceries.html">Groceries</a></li>
        <li><a href="contact.html">Contact</a></li>
      </ul>
    </nav>
  </footer>
  <script type="text/javascript">

    window.addEventListener("DOMcontentLoaded", function(e){
    const orderButtons= document.querySelectorAll("button[data-order]");

      orderButtons.forEach(function(button){
        button.addEventListener("click",function(e){
          const button= e.currentTarget;
          const container= button.parentNode;

          const order={
            id:button.getAttribute("data-order"),
            title: container.querySelector(".title").innerText,
            price1: container.querySelector(".Price").innerText,
            desc:container.querySelector(".desc").innerText
          };

          localStorage.setItem('order', JSON.stringify(order));

          const url = window.location.href.replace("grc.html","order.html");
          window.location.href = url;
        });
      });




    });
    window.addEventListener("DOMcontentLoaded", function(e){
      console.log("The page is loaded.");
    });
    const orderButtons= document.querySelectorAll("button[data-order]");
    orderButtons.forEach(function(button){
      button.addEventListener("click", function(e){
        console.log("The button was clicked.");
      });
    });
  </script>

</body>

</html>

  **Below is what I see when I run the live server**

<!-- Code injected by live-server -->
<script type="text/javascript">
    // <![CDATA[  <-- For SVG support
    if ('WebSocket' in window) {
        (function() {
            function refreshCSS() {
                var sheets = [].slice.call(document.getElementsByTagName("link"));
                var head = document.getElementsByTagName("head")[0];
                for (var i = 0; i < sheets.length; ++i) {
                    var elem = sheets[i];
                    head.removeChild(elem);
                    var rel = elem.rel;
                    if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() == "stylesheet") {
                        var url = elem.href.replace(/(&|\?)_cacheOverride=\d+/, '');
                        elem.href = url + (url.indexOf('?') >= 0 ? '&' : '?') + '_cacheOverride=' + (new Date().valueOf());
                    }
                    head.appendChild(elem);
                }
            }
            var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://';
            var address = protocol + window.location.host + window.location.pathname + '/ws';
            var socket = new WebSocket(address);
            socket.onmessage = function(msg) {
                if (msg.data == 'reload') window.location.reload();
                else if (msg.data == 'refreshcss') refreshCSS();
            };
            console.log('Live reload enabled.');
        })();
    }
    // ]]>
</script>
</body>

</html>

【问题讨论】:

  • price1: container.querySelector(".price").innertext 如果您使用此元素内部的任何内容来设置价格,任何人都可以通过使用开发工具检查它来更改它。
  • “因此不会重定向到新页面” - 重定向不依赖于实际存储在本地存储中的内容。因此,如果没有发生重定向,则完整的处理程序函数没有运行(不太可能,尽管您应该将 console.log 放入 that 函数以确保一切正常,而不是添加 额外的 一个除了登录到控制台之外什么都不做的) - 或者您的代码遇到错误,从而停止了进一步的脚本执行。浏览器控制台有什么要说的?当您在调试器中单步执行代码时会发生什么?
  • 我已经上传了我在调试器中看到的内容,希望它能为这种情况添加更多上下文

标签: javascript json function local-storage location-href


【解决方案1】:

在代码挂钩时,DOMcontentLoaded 事件已经触发。

查看这篇文章;

Code inside DOMContentLoaded event not working

【讨论】:

  • 谢谢,这实际上给了我们想要的结果。尽管我们已经获得了坚持执行任务的步骤,并且加载的 DOM 内容似乎在其中
【解决方案2】:

这里的问题是事件DOMContentLoaded 没有触发。 以下是我使用 load 事件的方法;对于重定向,我只是使用了URL search params(因为我不知道您的其他 html 文件是什么样的),尽管您可以使用您的其他 html 文档。

sn-p 在下面

但请注意:Stackoverflow 不允许 JavaScript 运行,并且会抛出 securityError。要运行此代码,您必须将其保存在您的计算机上或使用 jsFiddle

function continue_ordering() {
  alert("Now continue with order");
};

window.addEventListener("load", function(e) {
  const orderButtons = document.querySelectorAll("button[data-order]");
  orderButtons.forEach(function(button) {
    button.addEventListener("click", function(e) {
      const button = e.currentTarget;
      const container = button.parentNode;
      const id = button.getAttribute("data-order");
      const order = {
        id,
        title: container.querySelector(".title").innerText,
        price1: container.querySelector(".price").innertext,
        desc: container.querySelector(".desc").innerText
      };
      localStorage.setItem("order-" + id, JSON.stringify(order));
      window.location.search = "?ordering=true&order-id=" + id;
    });
  });
});
window.addEventListener("load", function(e) {
  if (window.location.search.search("ordering=true") != -1) {
    console.log("User is ordering");
    const params = new URLSearchParams(location.search)
    const id = params.get("order-id");
    if (!id || id == null) throw "There is no order id, error. Remove the ?ordering=true from the url and try again.";

    const order_info = JSON.parse(localStorage.getItem("order-" + id));
    if (!order_info) throw "Order information is not present: try ordering again. Remove the ?ordering=true from the url";
    console.log("Order info is:\n", order_info);
    document.getElementById("ordering").removeAttribute("hidden");
    return;
  };
  document.getElementById("make-order").removeAttribute("hidden");
});
const orderButtons = document.querySelectorAll("button[data-order]");
orderButtons.forEach(function(button) {
  button.addEventListener("click", function(e) {
    console.log("The button was clicked.");
  });
});
<div id="make-order" hidden>
  <button data-order="test">Order</button>
  <div class="title">This is the title</div>
  <div class="price">130 USD</div>
  <div class="desc">Lorem</div>
</div>
<div id="ordering" hidden>
  <h1>
    You are ordering.
    <br> Choose
    <a href="javascript:location.search='';">Stop ordering</a> Or <a href="javascript:continue_ordering();">Continue with order</a>
  </h1>
</div>

【讨论】:

    猜你喜欢
    • 2017-06-24
    • 2016-11-10
    • 2017-12-06
    • 2012-02-23
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多