我正在尝试弄清楚如何从每个答案中得分

时间:2017-12-12 20:48:14

标签: javascript

我正在尝试将每个问题的分数相加,并在提交for后报告分数。我觉得我很接近,但仍然不确定我哪里出错了。

JavaScript的:

let score = 0
for (i = 0; i < score.length; i++);

const button = $('#submit')
button.on('click', secondQ)

function firstQ () {
  let answer = $('#Q1').val()
  if (answer === 'Back') {
    score = score + 1
    console.log()
  } else if (answer === '') {
    alert('Please enter an answer.')
  }
  event.preventDefault()
}

function secondQ () {
  let answer = $('#Q2').val()
  if (answer === 'Chow Chow') {
    score = score + 1
    console.log(score)
  } else if (answer === '') {
    alert('Please enter an answer.')
  }
  event.preventDefault()
}

const input = $('input')
input.keypress(function (event) {
  if (event.which == 13) {
    event.preventDefault()
  }
})

1 个答案:

答案 0 :(得分:0)

您的HTML示例

<input type="text" id="Q1" class="getScore">
<input type="text" id="Q2" class="getScore">
<button type="submit" id="submit">SUBMIT</button>
<p class="scoreDiv">Your Score is: <span id="score"></span></p>

找到HTML元素的JS&amp;增加分数

let score = 0

function showScores() {
    $('#score').append(score);
}

const button = $('#submit')
button.on('click', function() {
  firstQ();
});

function firstQ() {
  let answer = $('#Q1');
  if (answer.val() === 'Back') {
    score++
        if (answer.hasClass('invalid')) {
        answer.removeClass('invalid');
    }
    secondQ();
  } else {
    addInvalid(answer);
  }
}

function secondQ() {
  let answer = $('#Q2');
  if (answer.val() === 'Chow Chow') {
    score++
    if (answer.hasClass('invalid')) {
        answer.removeClass('invalid');
    }
    showScores();
  } else {
    addInvalid(answer);
  }
}

function addInvalid(el) {
  $(el).css('border', '1px solid red').addClass('invalid').attr('placeholder', 'Please enter an answer.');
}