我正在尝试制作一个简单的线性文本游戏,该游戏将显示在网页的 div 内。我正在使用 innerHTML 将游戏的内容写入 div,并使用按钮中的 onclick 来更改内容。我的问题是我还想包含一些用户提交的变量,我试图在函数中使用 prompt() 来实现。
问题是,我无法让变量全局设置。它在函数内部调用时起作用,但在其他任何地方都不起作用。
我尝试使用 window.variable (在函数内部和外部)首先在函数外部声明变量,并在函数内部保留var
变量之前的变量以使其在范围内成为全局变量。
我一直在寻找解决方案,但似乎没有任何效果!我的脚本顺序是否遗漏了什么?
这是javascript:
var cb2 = '<input id="button" type="button" value="Continue" onclick="replace(\'gamebox\',next3,\'continueBttn\',cb3);">';
var cb3 = '<input id="button" type="button" value="Continue" onclick="getName();">';
var cb4 = '<input id="button" type="button" value="Continue" onclick="replace(\'gamebox\',next5,\'continueBttn\',cb5);">';
var cb5 = '<input id="button" type="button" value="Continue" onclick="replace(\'gamebox\',next6,\'continueBttn\',cb6);">';
var testName = "Test Name";
var player1;
var next2 = "<p>Great, you've certainly got an adventurer's spirit! Now I just need a few details about you and your party.</p>";
var next3 = "<p>First, I'd like to get everyone's name</p>"
var next4 = "<p>Thanks " + testName + "!</p>"
var next5 = "<p>Now you're ready " + player1 + "! Click to set out on the trail!</p>"
var continueButton = function (content) {
document.getElementById('continueBttn').innerHTML = content;
};
function replace(id1,content,id2,cb) {
document.getElementById(id1).innerHTML = content;
document.getElementById(id2).innerHTML = cb;
}
function getName() {
player1 = prompt("What is your Name?");
alert("Your name is " + player1 + ".");
replace('gamebox',next4,'continueBttn',cb4);
}
这是html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="oregon.css" />
</head>
<body>
<div id="gameContainer">
<div id="gamebox">
<p>Welcome to the Oregon Trail! Click Continue to travel the trail!</p>
</div>
</div>
<div id="continueBttn"><input id="button" type="button" value="Continue" onclick="replace('gamebox',next2,'continueBttn',cb2);"></div>
</body>
</html>
<script src="oregon.js" type="text/javascript"></script>