2016-12-15 38 views
0

我從JSON數據庫中提取數據並根據其ID在DIV中顯示產品。如果ID匹配,它會在DIV中顯示正確的項目及其內容。需要重新加載JSON,具體取決於窗口位置哈希

我試着改變邏輯,讓它根據產品UPC是否匹配window.location.hash顯示產品。這適用於第一個項目,但沒有其他項目。到目前爲止沒有運氣。希望有人能幫助我解決這個問題。以下是我的代碼謝謝。

var itemName = ''; 
var itemUPC = ''; 
var itemDesc = ''; 
var itemOZ = ''; 
var itemImage = ''; 

var compareHash = window.location.hash; 
var compareUPC = ''; 

$.each(json, function(i, item) { 

    compareUPC += '#' + item.itemFullUPC; 

    if (compareHash == compareUPC) { 

    itemName += '<h1>' + item.itemName + '</h1>'; 
    itemUPC += item.itemFullUPC; 
    itemDesc += '<p>' + item.itemDescription + '</p>'; 
    itemOZ += '<h2>' + item.itemPackSize + '</p>'; 
    itemImage += '<img class="img-responsive img-rounded center-block" src="' + item.imageURL + '">'; 
    } 

    $('#productTitle').html(itemName); 
    $('#productUPC').html(strippedUPC); 
    $('#productDescription').html(itemDesc); 
    $('#productOZ').html(itemOZ); 
    $('#productImage').html(itemImage); 


}); 
+0

樣本? + =將以前的結果與新的結果一致... – Nico

+0

@Nico你建議我改變什麼? – Tom

回答

1

你可能想onhashchange

if ("onhashchange" in window) { 
    alert("The browser supports the hashchange event!"); 
} 

function locationHashChanged() { 
    compareUPC += '#' + item.itemFullUPC; // or whatever you need to test here 
    if (compareHash == compareUPC) { 
     getJSON(); 
    } 
} 

// window.onhaschange=locationHashChanged; // or  
$(window).on("hashchange",locationHashChanged); 
+0

謝謝你看起來像它會工作!你得到的JSON函數是在哪裏放置每個循環? – Tom

+0

是的:) - 我認爲你還需要ajax的JSON或在那裏 – mplungjan

+0

好極了!謝謝你哦!我會試試這個 – Tom