功能无需点击' li'

时间:2016-04-28 00:41:16

标签: javascript jquery oop

我正在制作一个基本的猜谜游戏,我希望用户点击一个数字然后将该号码设为userAnswer,而computerAnswer是一个随机生成的数字,介于1到10之间。

无论如何,setVariables()函数在没有用户点击li的情况下运行,即使我将它设置为点击。

任何帮助都会很棒!

HTML

<!DOCTYPE html>
<html lang="en" class="no-js">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Animated Background Headers | Demo 2</title>
        <meta name="description" content="Examples for creative website header animations using Canvas and JavaScript" />
        <meta name="keywords" content="header, canvas, animated, creative, inspiration, javascript" />
        <meta name="author" content="Codrops" />
        <link rel="shortcut icon" href="../favicon.ico">
        <link rel="stylesheet" type="text/css" href="css/normalize.css" />
                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.2.1/foundation.min.css">
        <link rel="stylesheet" type="text/css" href="css/demo.css" />
        <link rel="stylesheet" type="text/css" href="css/component.css" />
                <link rel="stylesheet" type="text/css" href="dist/css/app.css">
        <link href='http://fonts.googleapis.com/css?family=Raleway:200,400,800|Clicker+Script' rel='stylesheet' type='text/css'>
        <!--[if IE]>
            <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    </head>
    <body>

        <div class="container demo-2">
            <div class="content">
                <div id="large-header" class="large-header">
                    <canvas id="demo-canvas"></canvas>
                                        <div class="row enter-name">
                                        <div class="large-12 columns">
                                          <h1>The Guessing Game</h1>
                                          <p>This is a simple guessing game.</p>
                                          <h5>Please enter your name below</h5>
                                          <input type="text" id="name" value="" placeholder="John Doe">
                                          <input onclick="game.init()" type="submit" id="submit-name">
                                        </div>
                                        </div>
                                            <div class="row game hide">
                                                <div class="large-12 columns">

                                                    <h1 id="display-name" class="text-center"></h1>

                                                    <h1 class="text-center">Try to guess the number in less than 5 tries!</h1>

                                                    <ul class="numbers-to-guess">
                                                        <li value="1">1</li>
                                                        <li value="2">2</li>
                                                        <li value="3">3</li>
                                                        <li value="4">4</li>
                                                        <li value="5">5</li>
                                                        <li value="6">6</li>
                                                        <li value="7">7</li>
                                                        <li value="8">8</li>
                                                        <li value="9">9</li>
                                                        <li value="10">10</li>
                                                    </ul>

                                                    <hr />

                                                        <h2 id="user-name"></h2>
                                                        <div class="demo2">
                                                            <h2>The Computer's Number: <span id="demo1"></span></h2>
                                                        </div>

                                                        <div class="demo3">
                                                            <h2>Your Number: <span id="your-number"></span></h2>
                                                        </div>

                                                        <h2>Times Guessed: <span id="guessed"></span></h2>

                                                    <hr />

                                                        <h1 id='message'></h1>

                                                        <h3 class="score">Score: <span id="count"></span></h3>
                                                </div>

                                                <div class="large-5 columns answers">

                                                    <table class="large-5 text-center columns">
                                                        <tr>
                                                            <th>Computer's Answers</th>
                                                        </tr>
                                                        <tr id="computer-answers">
                                                        </tr>
                                                    </table>

                                                    <table class="large-5 text-center columns">
                                                        <tr>
                                                            <th id="user">User's Answers</th>
                                                        </tr>
                                                        <tr id="user-answers">
                                                        </tr>
                                                    </table>


                                                </div>
                                            </div>
                                      </div>
                </div>
            </div>
        </div><!-- /container -->
                <script src="js/app.js"></script>
        <script src="js/rAF.js"></script>
        <script src="js/demo-2.js"></script>
    </body>
</html>

JAVASCRIPT

(function(){

  // Players
  // Goals
  // Obstacles
  // Scoring System
  // UI for game
  // Game flow scroing -> points -> etc

  game = {
    init: function() {
      console.log('init');
      this.timesGuessed = 0;
      this.userAnswers = [];
      this.computerNumbers = [];
      this.cacheDom();
      this.setName();
      this.screenTransition();
      this.bindEvents();
    },

    cacheDom: function() {
      this.numbers = $('.numbers-to-guess');
      console.log(this.numbers);
    },

    setName: function() {

      this.userName = $('#name').val();
      this.setNameOnGame(this.userName);

    },

    bindEvents: function() {
      console.log(this.numbers.find('li'));
      this.numbers.find('li').on('click', this.setVariables());
    },

    screenTransition: function() {

      $('.enter-name').addClass('hide');
      $('.game').removeClass('hide');

    },

    setVariables: function() {
      console.log('set');
      console.log($(this));
      // Asks for users answer
      // this.userAnswer = prompt('Pick a number between 1 and 10');
      this.userAnswers.push(userAnswer);

      // Generates a random number between 1 and 10
      // this.randNumber = Math.floor(Math.random() * 10 ) + 1;
      this.computerNumbers.push(this.randNumber);

      // Checks the users number vs the random number
      this.checkAnswer(userAnswer, this.randNumber);
    },

    setNameOnGame: function(userName) {
      document.getElementById('user-name').innerHTML = 'Player Name: ' + userName;
      document.getElementById('user').innerHTML = userName + ' Answers';
      // document.getElementById('display-name').innerHTML = 'Hello ' + userName + '! Please pick a number below.';
    },

    checkAnswer: function(userAnswer, randNumber) {

      this.timesGuessed++
      this.render(userAnswer, randNumber, this.timesGuessed);

      if (userAnswer > randNumber) {
        alert('You Guessed To High, Guess Again...');
        document.getElementById('message').innerHTML = "You guessed to high";
        // this.setVariables();

      } else if (userAnswer < randNumber) {
        alert('You Guessed To Low, Guess Again...')
        document.getElementById('message').innerHTML = "You guessed too low";
        // this.setVariables();

      } else if(userAnswer = randNumber) {
        alert('You Got It Right!');
        document.getElementById('message').innerHTML = "You Guessed Right!";
      }

      this.score(this.timesGuessed);
      this.showAnswers();
      this.restartGame();

    },

    render: function(userAnswer, randNumber, timesGuessed) {
      document.getElementById('demo1').innerHTML = randNumber;
      document.getElementById('your-number').innerHTML = userAnswer;
      document.getElementById('guessed').innerHTML = timesGuessed;

    },

    score: function(timesGuessed) {
      if(timesGuessed <= 5) {
        document.getElementById('count').innerHTML = "You Won! It took you " + this.timesGuessed + " try(s) to guess the right number!";
      } else if (timesGuessed > 5) {
        document.getElementById('count').innerHTML = "Sorry! You Lost... It took you " + this.timesGuessed + " try(s) to guess the right number.";
      }
    },

    showAnswers: function() {
    // Show all answers
      for (var i = 0; i < this.computerNumbers.length; i++) {
        var listItem = document.createElement('TD');
        var listItemText = document.createTextNode(this.computerNumbers[i]);
        listItem.appendChild(listItemText);
        document.getElementById('computer-answers').appendChild(listItem);
      }

     // Show all guesses
      for (var i = 0; i < this.userAnswers.length; i++) {
        var listItem = document.createElement('TD');
        var listItemText = document.createTextNode(this.userAnswers[i]);
        listItem.appendChild(listItemText);
        document.getElementById('user-answers').appendChild(listItem);
      }
    },

    restartGame: function() {
      document.getElementById('start-btn').innerHTML = 'Play Again';
    }
  };

})();

这是我的控制台

enter image description here

2 个答案:

答案 0 :(得分:1)

使用您的代码,您正在调用该函数并设置它返回到单击处理程序的任何内容

this.numbers.find('li').on('click', this.setVariables());

您需要做的是分配对方法的引用。您需要使用bind(),因此其范围是游戏对象。

this.numbers.find('li').on('click', this.setVariables.bind(this));

答案 1 :(得分:1)

最后()立即调用该函数;把它留下来就应该好了。

 .... .on('click', setVariables )