0

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

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

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

产品链接

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

产品.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。

4

2 回答 2

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要通过from解析值,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')
    }));
});
于 2013-10-09T17:15:07.240 回答
1

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

像这样存储参数:

$('.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
});
于 2013-10-09T19:08:28.170 回答