Мне нужно получить значение inputScore
, которое в данный момент содержится в функции extractVariable
, в функцию assignValue
(эта функция возвращает значение inputScore
странице Index.html).Я пытался сохранить inputScore
в глобальном объекте для решения проблем области, но внутри assignValue
переменная global.scoreValue
не определена.Как я могу получить inputScore в assignValue, пожалуйста?Новое в программировании - любая помощь приветствуется.Спасибо.
global = {};
function extractVariable(inputScore) {
global['scoreValue'] = inputScore;
};
function assignValue() {
document.getElementById("inputScore").value = global.scoreValue;
};
Спасибо всем за помощь.Я так близок к решению того, что мне нужно сделать.Кажется, проблема заключается в получении inputScore
на странице Index.html
.Я должен был опубликовать весь мой код в первую очередь.Извиняюсь.index.html
- это отдельный файл, который имеет ссылку на файл javascript (Game.js
).Я проверил ссылку, и она работает.Когда кнопка нажата в Game.js
, index.html
загружается, считывает функцию assignValue
в Game.js
и вставляет счет игрока (inputScore
) во входное значение в форме.На данный момент все, что вставляется в форму: ![enter image description here](https://i.stack.imgur.com/Qirkp.jpg)
Я не могу понять, почему она не работает.Я включил код из обоих файлов ниже.Любая помощь еще раз приветствуется.
Код Game.js:
function extractVariable(inputScore) {
return inputScore;
};
function assignValue(inputScore) {
document.getElementById("playerScore").value = inputScore;
};
var CrystalRunner = CrystalRunner || {};
CrystalRunner.GameState = {
init: function() {
//...code here
},
create: function() {
//...code here
},
update: function() {
//..code here
//check if the player needs to die
if(this.player.top >= this.game.world.height) {
this.gameOver();
}
},
gameOver: function(){
//..code here
this.updateHighscore();
//..code here
},
updateHighscore: function(){
this.highScore = +localStorage.getItem('highScore');
if(this.highScore < this.myScore){
this.highScore = this.myScore;
this.inputScore = this.highScore;
this.submitScoreButton = this.game.add.sprite(this.game.world.centerX-135, this.game.world.centerY+100, 'submitScoreButton');
this.submitScoreButton.events.onInputUp.add(function() {
window.location.href = "index1.php";
}, this);
extractVariable(this.inputScore);
}
localStorage.setItem('highScore', this.highScore);
},
};
Index.html код:
<?php
require_once 'dbconnect.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Crystal Candy Game Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css"/>
<link href="css/style.css" rel="stylesheet">
</head>
<body onload="assignValue(extractVariable())" class="bg">
<div id="preloader">
<div id="status"> </div>
</div><!--preloader-->
<div class="wrapper">
<div id="main">
<!-- Form -->
<form id="form-style" method="post" action="crystalhandle.php" autocomplete="off">
<div class="form-group">
<label class="header-text"><span>First Name</span></label>
<input class="form-control" type="text" id="name" name="username" placeholder="Name" title="Please enter your Firstname" required="">
</div>
<div class="form-group">
<label class="header-text"><span>Score</span></label>
<input class="form-control" type="tel" id="playerScore" name="score" value="" readonly>
</div>
<div class="w3ls-btn form-group">
<div class="wthreesubmitaits">
<input type="submit" name="signup" id="reg" class="button" id="next1" value="Send" style="font-family: sans-serif; font-size: 17px; font-weight: bold;"
</div>
</div>
</form>
</div>
</div>
<div id="bodytext"></div>
<script type='text/javascript' src='js/jquery-2.2.3.min.js'></script>
<script type="text/javascript" src="js/phaser.min.js"></script>
<script type="text/javascript" src="js/states/Game.js"></script>
<script>
$(window).on('load', function() {
$('#status').fadeOut();
$('#preloader').delay(350).fadeOut('slow');
$('body').delay(350).css({'overflow':'visible'});
})
</script>
</body>
</html>
Я сделал следующие изменения, я думаюрешение под рукой.В Index.html
я изменил следующую строку, удалив inputScore
:
<body onload="assignValue(extractVariable())" class="bg" >
В Game.js
я обнаружил, что если я жестко закодирую значение в функцию extractVariable
(см. Ниже),закодированное значение передается в атрибут value
тега <input>
в Index.html
, что я и хочу.Тем не менее, я до сих пор не могу понять, почему это работает только с жестко закодированным значением?
function extractVariable(inputScore) {
inputScore = 27; //hard coded value works. Why?
return inputScore;
};
function assignValue(inputScore) {
console.log(inputScore); //this console.logs the hard coded value from
//extractVariable like it should do
document.getElementById("playerScore").value = inputScore;
};