2017-06-05 103 views
-2

我創建了一個藝術家(artists.html)頁面,其中包括大約15位藝術家。現在我正試圖通過動態的單個HTML文件來創建每位藝術家的個人資料。所以我創建了另一個HTML文件(single-artist.html),它將顯示訪問者點擊的藝術家的個人資料。如何在點擊時從JSON文件動態獲取數據?

artists.html(滿分15名藝術家,下面是兩個例子)

<div class="all-artist" id="artists"> 
      <div class="col-md-4 col-sm-6 col-xs-6 artist-single" data-number="0"> 
       <div> 
        <a href="artist-single.html"> 
         <img src="img/1.jpg" alt=""> 
        </a> 
       </div> 
      </div> 

      <div class="col-md-4 col-sm-6 col-xs-6 artist-single" data-number="1"> 
       <div> 
        <a href="artist-single.html"> 
         <img src="img/2.jpg" alt=""> 
        </a> 
       </div> 
      </div> 

    </div> 

藝術家single.html

<div id="name"></div> 
<div id="logo"></div> 
<div id="bio"></div> 

data.json

[{ 

"name": "Arsh", 
"logo": "img/logo.jpg", 
"bio": "Arsh is a singer/songwriter" 

}, 

{ 

"name": "Benz", 
"logo": "img/logo.jpg", 
"bio": "Benz is a singer" 

}] 

主。 js

$('#all_artists artist-single').on('click',function(){ 
window.location.href="artist-single.html"; 
var num = $(this).data('number'); 
$.getJSON('data.json',function(data) { 
    $('#name').html(data[num].name); 
    $('#description').html(data[num].bio); 
    $('#logo').append('<img src=data[num].logo>'); 
    }); 
}); 

現在,當我點擊藝術家圖像時,它會重定向到artist-single.html,但它不會提取值。也許是因爲我正在重定向並獲取同一事件的值。幫助將非常感激。

+1

在重定向後運行的代碼將被中止。您應該在另一頁上的文檔就緒功能中執行該部分。 – madebydavid

+0

您需要等到新頁面加載完畢。 https://stackoverflow.com/questions/15589401/changing-window-location-then-waiting-for-the-window-to-load –

回答

-1
$(document).ready(function() { 
    var num = $.cookie('num'); 

    $.getJSON('data.json', function(data) { 
    $('#name').html(data[num].name); 
    $('#description').html(data[num].bio); 
    $('#logo').append('<img src=data[num].logo>'); 
    }); 

    $('#artists .artist-single').on('click', function() { 
    var num = $(this).data('number'); 
    $.cookie('num', num); 
    window.location.href = "artist-single.html"; 
    }); 

}); 
+0

嘿威廉,謝謝你的回答,但我恐怕它仍然無法正常工作。 –