Webページの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>