var answers = ['B','B','B','B','B','B'];
var score=0;
var total = answers.length;
function getCheckedValues(radioName) {
var radios=document.getElementsByName(radioName);
for(var i=0;i<radios.length;i++) {
if(radios[i].checked) return radios[i].value;
}
}
function check_score() {
for(var i=0;i<total;i++) {
if(answers[i]==getCheckedValues("question"+i))
score++;
}
returnScore();
}
function returnScore() {
window.open("score_display.php");
}
window.onload=function congratulations_message() {
if(score>3)
document.getElementById('score-display').innerHTML="<h1>Your Score is:</h1><h2>"+score+"</h2>"+"<h1>Congratulations, You are on a path to glory!!!</h1>";
else {
document.getElementById('score-display').innerHTML="<h1>Your Score is:</h1><h2>"+score+"</h2>"+"<h1>Oops!!! Hard Luck! Better luck next time</h1>";
}
}
在上面的代码中,我使用变量得分来计算问答游戏的得分。当我转到“ score_display.php”(另一个显示“ score”作为祝贺消息的页面)时,score的值变为0。我假设由于score是全局变量,因此可以在我使用的不同html文件中使用链接了我的JavaScript文件。我的假设我错了吗?
有什么办法可以保留“分数”的价值?
最佳答案
首先,您不能在页面之间传递javascript变量,新页面不在范围内。看一下帖子“ Persist variables between page loads”。
在这种情况下,有许多解决方案可以使用,例如localStorage, cookies, windows.name...
,但是我建议一个简单的解决方案,您可以使用GET方法将score
变量作为参数传递给php文件score_display.php
,例如:
function check_score() {
for(var i=0;i<total;i++) {
if(answers[i]==getCheckedValues("question"+i))
score++;
}
returnScore(score);
}
function returnScore(_score) {
window.open("score_display.php?score="+_score);
}
然后,可以在另一端(服务器端)使用
$_GET['score']
将其显示在PHP代码中。