单击列表项后设置对象键/值对

时间:2017-09-27 04:47:02

标签: javascript jquery

我试图将Object属性设置为等于单击列表项(0,1,2,3)的值。我能够在console.log中找到正确的值,但是没有设置object属性。

有人可以解释一下如何将我的gameObject属性设置为正确的列表项值吗?



var gameObject = {
  questions: [
    {
      title: "What color is the sky?",
      answers: [
        "blue",
        "green",
        "red",
        "purple"
      ],
      correctAnswer: 0,
      userSelection: ''
    },
    {
      title: "What color is UNC blue?",
      answers: [
        "Duke blue",
        "Sky blue",
        "red",
        "purple"
      ],
      correctAnswer: 1,
      userSelection: ''
    },
    {
      title: "What color is UNC blue?",
      answers: [
        "Duke blue",
        "Sky blue",
        "red",
        "purple"
      ],
      correctAnswer: 1,
      userSelection: ''
    },
  ],
  currentQuestion: 0,
  userCorrect: 0,
  userIncorrect: 0,
  userBlank: 0,
  timer: 30,
  timerRunning: false
};

var triviaAnswerSection = $('#answers');

function renderGameAnswers() {
  var html = '';
  html += `<ul class='question'>`
  html += `<li class='answer' value='0'><a href='#'>${gameObject.questions[gameObject.currentQuestion].answers[0]}</a></li>`
  html += `<li class='answer' value='1'><a href='#'>${gameObject.questions[gameObject.currentQuestion].answers[1]}</a></li>`
  html += `<li class='answer' value='2'><a href='#'>${gameObject.questions[gameObject.currentQuestion].answers[2]}</a></li>`
  html += `<li class='answer' value='3'><a href='#'>${gameObject.questions[gameObject.currentQuestion].answers[3]}</a></li>`
  html += `</ul>`
  triviaAnswerSection.html(html);
  $('.answer').on('click', function() {
    var answer = $(this).attr('value');
    gameObject.questions[gameObject.currentQuestion].userSelection = answer;
  });
}

renderGameAnswers();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div id='game'>
  <div id='title'>
  </div>
  <div id='start'>
  </div>
  <div id='stop'>
  </div>
  <div id='timeRemaining'>
  </div>
  <div id='questions'>
  </div>
  <div id='answers'>
  <div id='done'>
  </div>
  <div id='userScore'>
  </div>
</div>
</body>
</html>
&#13;
&#13;
&#13;

0 个答案:

没有答案