2017-09-26 36 views
0

我有一個頁面上的按鈕另一個頁面上的另一個按鈕。此第二個按鈕的文本中包含「已選擇0個項目」。當第一個按鈕被點擊時,我想增加第二個按鈕中的數字。如何在jQuery中使用會話變量?

看到它正在通過不同的頁面傳輸數據我沒有設法做到這一點的標準方式。

請不要暗示PHP,我無法使用它。

var yetVisited = localStorage[0]; 
 

 
if ($('.#CallToActionCustomise').click()){ 
 
\t localStorage++; 
 
} 
 
$('.#CallToActionCustomise').click(function(){ 
 
\t $(".Main_MenuButtonReview").append(localStorage); 
 
});
<button class="Main_MenuButtonReview">0 items selected <i class="fa fa-caret-down"></i></button>

+0

localStorage不是數組。這是一個對象。你不能增加一個對象?在localStorage中定義一個變量,它將工作:'localStorage.myCounter'例如 –

回答

1

你需要訪問的localStorage就好像它是一個對象,而不是一個數組。

此外,您只能存儲字符串值,因此要獲得一個數字來執行數學運算,您將需要使用parseInt

localStorage.setItem('yetVisited', 0); 

$(".Main_MenuButtonReview").text(localStorage.yetVisited + ' items selected'); 

$('.CallToActionCustomise').click(function()){ 
    localStorage.yetVisited = parseInt(localStorage.yetVisited) + 1; 
    $(".Main_MenuButtonReview").text(localStorage.yetVisited + ' items selected'); 
} 

這是example

+0

似乎沒有顯示數字,我是否需要添加任何東西到這個工作的HTML? – Dale

+0

你在if語句中有你的事件監聽器。這可以防止它被添加。我沒有理解,但我會更新答案。 – Bricky

+0

仍然無法工作抱歉。我不確定我做錯了什麼。有沒有其他方法可以做到這一點? – Dale

0

除了上面的答案,我認爲你需要在加載時初始化一些標籤。

將此代碼放入另一個頁面。

$(document).ready(function() { 
    if (typeof localStorage.yetVisited === 'undefined') { 
     localStorage.setItem('yetVisited', 0); 
    } 
    yetVisited = localStorage.yetVisited; 
    $('.Main_MenuButtonReview').text(yetVisited + ' items selected'); 
}); 

$(document).ready(function() { 
// this area means after your page(document) ready completely. 
});