0

20 ほどの製品が掲載された製品ページがあります。製品リンクをクリックすると、リダイレクト先のページに 2 つのパラメーター、画像 src とテキスト属性を渡し、これらを div に表示したいと考えています。

ATM 私のコードは title と img data 属性を設定し、URL 文字列の属性を使用して正しいページにリダイレクトしますが、この情報を適切に表示する方法がわかりません。

title と img の両方の属性パラメータをlineup/index.htmlページに渡して、これら2つの属性を表示するにはどうすればよいですか? また、属性を 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 だけを使用しています。

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から値を解析するには、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.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
});
于 2013-10-09T19:08:28.170 に答える