2013-10-09 39 views
0

我有一個包含20個左右產品的產品頁面。當你點擊一個產品鏈接時,我想將2個參數傳遞給它重定向到的頁面,一個圖像src和一個文本屬性,然後顯示在div中。重定向到頁面並傳遞文本和圖像參數 - HTML JS

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

​​

陣容/ index.html的

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

如果有人需要更多的代碼就罵,我用的只是普通的HTML, JavaScript和jQuery。

回答

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; 
    }); 
}); 

url解析由key一個值,你可以使用此功能(來源: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') 
    })); 
}); 
+1

這就是偉大的感謝!完善。 – dodgerogers747

+0

不客氣:-) –

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 
}); 
相關問題