Получить значение из одной функции и поместить его в другую функцию - PullRequest
0 голосов
/ 13 декабря 2018

Мне нужно получить значение 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
Я не могу понять, почему она не работает.Я включил код из обоих файлов ниже.Любая помощь еще раз приветствуется.

Код 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">&nbsp;</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;

};

Ответы [ 5 ]

0 голосов
/ 14 декабря 2018

Я наконец-то решил это.Вот решение для всех, кто заинтересован.Я включил код Game.js с комментариями, чтобы показать, что я сделал.Index.html остается таким, каким я его редактировал в вопросе.Спасибо всем, кто помог.

    function extractVariable(inputScore) {

  inputScore = +localStorage.getItem('highScore'); //we then define inputScore again 
by getting the score stored on local storage

  return inputScore; 

};



function assignValue(inputScore) {  

     document.getElementById("playerScore").value = inputScore;

};



var CrystalRunner = CrystalRunner || {};

CrystalRunner.GameState = {

init: function() {

  },


create: function() {

  },   


update: function() {  

      if(this.player.top >= this.game.world.height && this.counter === 0 || 
 this.player.left <= 0 && this.counter === 0) {
         this.gameOver();
      }


  },     


  gameOver: function(){

          this.updateHighscore();



      var style = {font: '40px Arial', fill: '#fff'};
     this.add.text(this.game.width/2, this.game.height/4, 'GAME OVER', 
style).anchor.setTo(0.5);


      style = {font: '30px Arial', fill: '#fff'};
      this.add.text(this.game.width/2, this.game.height/4 + 50, 'High score: ' + 
this.highScore, style).anchor.setTo(0.5);

      this.add.text(this.game.width/2, this.game.height/4 + 80, 'Your score: ' + 
this.myScore, style).anchor.setTo(0.5);

      style = {font: '18px Arial', fill: '#fff'};
      this.add.text(this.game.width/2, this.game.height/4 + 120, 'Tap/click to play 
again', style).anchor.setTo(0.5);


      this.game.input.onDown.addOnce(this.restart, this);


    }, this);

    gameOverPanel.start();
    this.counter++;

  },


  restart: function(){

    this.game.state.start('Game');
  },

  updateHighscore: function(){
    this.highScore = +localStorage.getItem('highScore');


    if(this.highScore < this.myScore){
            this.highScore = this.myScore;

      localStorage.setItem('highScore', this.highScore);

      this.inputScore= +localStorage.getItem('highScore'); //this input.Score needs 
      //to get it's value from localStorage and not this.highScore


            this.submitScoreButton = this.game.add.sprite(this.game.world.centerX- 
   135, this.game.world.centerY+100, 'submitScoreButton');
            this.submitScoreButton.inputEnabled = true;
            this.submitScoreButton.fixedToCamera = true;

            extractVariable(this.inputScore); //call extractVariable

            this.submitScoreButton.events.onInputDown.add(function() {


                        window.location.href = "index1.php";


                  }, this);

            }

       },


};
0 голосов
/ 13 декабря 2018

Я не могу понять, почему это не работает.

id s элементов HTML становятся глобальными переменными.

У вас есть элемент с id inputScore.

Вы указываете, что extractVariable должен вызываться с inputScore в качестве аргумента:

<body onload="assignValue(extractVariable(inputScore))" class="bg"> 

Таким образом, вы пытаетесь установить элемент DOM равным значению текстового ввода.Это не может работать.Строковое представление элемента DOM - это именно то, что вы видите на скриншоте

console.log(document.createElement('span').toString());

Мне не ясно, что вы ожидаете от inputScore здесь.Поэтому единственное предложение, которое я могу дать, - удалить обработчик onload.

0 голосов
/ 13 декабря 2018

Вы можете сделать это, вернув значение из extractVariable и передав его в качестве параметра в assignValue:

function extractVariable(inputScore) {
  return inputScore;
};


function assignValue(inputScore) {
  document.getElementById("inputScore").value = inputScore;
};

assignValue(extractVariable(inputScore));
0 голосов
/ 13 декабря 2018

Пожалуйста, используйте es6 и scoping with let - вот пример, который отлично работает:

let scoreValue = 0;

function extractVariable(inputScore) {

    scoreValue = inputScore;

};

function assignValue() {

    console.log(scoreValue);

};

extractVariable(200);
assignValue();
0 голосов
/ 13 декабря 2018

Вы должны вызвать или вызвать extractVariable () внутри assignValue ()

var global = {};
function extractVariable(inputScore) {
   global['scoreValue'] = inputScore;
};
function assignValue() {
  extractVariable('test');
  document.getElementById("inputScore").value = global.scoreValue;
};
assignValue();
<input id="inputScore"/>

Хотя использовать переменную в этом случае необязательно, вы можете просто вернуть значение из функции:

function extractVariable(inputScore) {
   return inputScore;
};
function assignValue(input) {
  document.getElementById("inputScore").value = input;
};
assignValue(extractVariable('test'));
<input id="inputScore"/>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...