【问题标题】:Getting Images from one page to show up on the following one从一页获取图像以显示在以下一页上
【发布时间】:2022-01-06 15:21:49
【问题描述】:

我正在尝试使用 JQuery 从图形标签中获取图像以显示在下一页上。这是我尝试使用的 JQuery 代码:

(() => {
    $("a").click(function(){
        this.prev().appendTo('#product');
    })
});

这是图形标签:

<figure id="tennis_set">
    <img class="shop_image" src="images/shop2.jpg" >
    <a href="seemore.html"><figcaption id="tennis_set_no_shoes">See more</figcaption></a></figure>

这是下一页上我想要的 div:

<div id="product_description_checkout">
                <h2 class="payment_title">Order Summary</h2>
                <div id="product"></div>
            </div>

到目前为止,它不起作用。我将不得不使用 Ajax 或 PHP 来存储数据吗?还是我只是为 JQuery 使用了错误的代码?

【问题讨论】:

  • 尝试将其存储在 localStorage 中,然后在下一页检索它
  • 喜欢这个?我可能做错了,但这也不起作用:
  • (() =&gt; { $("a").click(function(){ setItem("image", JSON.stringify(this.prev())); getItem("image").appendTo("#product"); }) });

标签: jquery css image responsive


【解决方案1】:

也许是这样的。将图像源作为变量设置到本地存储中。然后在下一页检查它。如果存在,则使用本地存储中的 src 创建一个图像元素。

$(document).ready(function() {
  $("a").click(function(e) {
    e.preventDefault();
    let src = $(this).closest('figure').find('img').attr('src');
    console.log('src', src);
    localStorage.setItem("useImage", src);
    // now that we got it stored, allow the link to go through
    window.location.href=$(this).attr('href');
  })
});

// on next page

$(document).ready(function() {
  if (!localStorage.getItem("useImage")) return;
  let img = $('<img />', {
    src: localStorage.getItem("useImage"),
  });
  img.appendTo($('#product'));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<figure id="tennis_set">
  <img class="shop_image" src="images/shop2.jpg">
  <a href="seemore.html">
    <figcaption id="tennis_set_no_shoes">See more</figcaption>
  </a>
</figure>

【讨论】:

  • 还是不行。
  • Doesn't work 对那些看不到你的代码试图在浏览器中执行的人来说没有任何意义。如果您需要帮助,请尝试确定是否存在错误或问题所在 - 然后发布
  • 对不起。你说得对。问题是,我没有收到任何错误消息。我可以猜测的是,之前应该存储图像 url 的代码没有这样做,但我不知道为什么。
  • 这是现在的代码: (() => { $("a").click(function(){ localStorage.setItem("image", this.prev().attr ('src')); }); }); //在下一页 (() => { if (!localStorage.getItem("image")) return; let img = $('', { src: localStorage.getItem("image"), } ); img.appendTo($('#product')); });
  • 我在代码中发现了一个错字(我不小心输入了this 而不是$(this))——然后我认为从figure 容器中引用图像可能会更好。尝试更新的代码,看看它是否有帮助。如果没有,请尝试console.log(localStorage('useImage')) 看看是否存储了正确的数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-11
  • 1970-01-01
  • 2018-08-07
  • 1970-01-01
  • 1970-01-01
  • 2013-03-11
相关资源
最近更新 更多