【问题标题】:Redirect to page and pass text and image parameter - HTML JS重定向到页面并传递文本和图像参数 - HTML JS
【发布时间】:2013-10-09 16:54:56
【问题描述】:

我有一个产品页面,上面有 20 种左右的产品。当您单击产品链接时,我想将 2 个参数传递给它重定向到的页面,一个图像 src 和一个文本属性,然后将它们显示在 div 中。

ATM 我的代码设置了标题和 img 数据属性,使用 URL 字符串中的属性重定向到正确的页面,但我不确定如何正确显示此信息。

如何将 title 和 img 属性参数同时传递给 lineup/index.html 页面,然后显示这两个属性?还有比将属性放在 URL 查询字符串中更好的方法吗?

产品链接

<a href="#" class="product" data-img="product1-img.jpg" data-title="Product1">More Information</a>

products.js

jQuery(document).ready(function($){
    $('.product').click(function(event) {
        var name;
        name = $(this).data('title');
        window.location = './lineup/index.html?title=' + name + 'img' + img;
    });
});

阵容/index.html

<div class="text_area">
    <div id="title-area">TITLE ATTRIBUTE</div>
    <div class="product-img">
      IMG SRC
    </div>
</div>

如果有人需要更多代码,请大喊,我只使用纯 HTML、javascript 和 jQuery。

【问题讨论】:

    标签: javascript jquery html parameters


    【解决方案1】:

    要同时传递两个参数,你可以试试这个

    jQuery(document).ready(function($){
        $('.product').click(function(event) {
            event.preventDefault();
            var name = $(this).data('title'), img = $(this).data('img')
            window.location = './lineup/index.html?title=' + name + '&img=' + img;
        });
    });
    

    要通过key 解析来自url 的值,您可以使用此函数(来源:MDN)

    function loadPageVar (sVar) {
        return decodeURI(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURI(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
    }
    

    在您的lineup/index.html 中输入这段代码和上面给出的函数

    $(function(){
        $('#title-area').text(loadPageVar('title'));
        $('.product-img').text(loadPageVar('img')); // will set text
    
        // To set an image with the src
        $('.product-img').append($('<img/>', {
            'src':loadPageVar('img')
        }));
    });
    

    【讨论】:

      【解决方案2】:

      如果您正在寻找 URL 查询字符串的替代方法,我会查看 window.sessionStorage 对象。

      像这样存储参数:

      $('.product').click(function(event) {
          event.preventDefault();
          window.sessionStorage.setItem('name', $(this).data('title'));
          window.sessionStorage.setItem('imgSrc', $(this).data('img'));
          window.location.reload(); //refreshes the page
      });
      

      然后加载属性,如果它们存在,添加以下内容:

      $(function(){
          if (window.sessionStorage.length){
              $('#title-area').text(window.sessionStorage.getItem('title'));
      
              $('.product-img').append($('<img/>', {
                  'src':window.sessionStorage.getItem('imgSrc')
              }));
          }
      
          //include the click event listener for .product link here too
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-24
        • 2019-02-22
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        相关资源
        最近更新 更多