2017-04-22 39 views
1

此前,我研究过一种方法来创建我的js变量team1score和team2score,即使在页面刷新后仍保留它的值。我发现问题最简单的解决方案是使用会话存储。我现在有了我的team1score和team2score保持其价值,以便解决问题。如何在使用会话存储刷新页面后初始化并保留更新的js变量的值?

但是,我现在有另一个问题。两队的初始分数应为0.因为我从未将team1score和team2score初始化为0,所以两队的初始分数目前都显示为空。我这样写我的代码,因为这是我的js变量保留其价值的唯一方法。

有谁知道我可以如何初始化team1score和team2score为0,同时在刷新页面后保留它们的值?提前致谢!

var team1score = sessionStorage.getItem('updatedScore1'); 
var team2score = sessionStorage.getItem('updatedScore2');  

if(turn == 1) 
{ 
    team1score += overallScore; 
    var teamOneScore = document.getElementById('team1score'); 
    alert('Team 1:'+team1score); 

    //created new variable that stores the current updated score 
    var updatedScore1 = team1score; 

    //stores this into the local storage 
    sessionStorage.setItem('updatedScore1', updatedScore1); 

    //retreives the variable from the local storage 
    var updatedScore1 = sessionStorage.getItem('updatedScore1'); 

    //displays this onto the html part of the code 
    teamOneScore.innerHTML = 'Team 1: '+updatedScore1; 

} 
+0

你想要的比分为0,您可以使用速记如果反过来== 0? –

+0

不,对不起,我可能没有提供足够的信息。如果turn == 1,那么球队1赢了,更新他们的分数。最初我已初始化team1score = 0,这确实显示正确,但当我试图让js变量保留其值时,我将其更改为team1score = sessionStorage.getItem('updateScore1');一旦我做了这个改变,js变量保留了它的价值,但团队成绩最初显示为空。我相信这是因为我从未初始化它们。 –

回答

1

如果其他使用这个

team1score = sessionStorage.getItem('updatedScore1') ? sessionStorage.getItem('updatedScore1') : 0; 
+0

最初没有工作,因为我有一个我忽略的小错误,但现在是!非常感谢! –

+0

很高兴,我可以帮忙。如果它适合您,请注册并标记为已接受。谢谢 –