简单的javascript JS事件处理程序无法正常工作

时间:2016-07-07 15:57:22

标签: javascript event-handling

以下是我的代码和随附的说明。目前,页面加载时会显示不正确答案的responseText,我无法将其更改为正确的答案。

// Declare a string variable called question and set it equal to a True/False question of your choice. 
var question = "KD has sold his legacy at OKC for a championship ring at GS.";

// Declare a boolean variable called answer and set it equal to true or false (the answer to the question you asked above.) 
var answer = true;

// Create a function called loadQuestion() that sets the value of the questionText element equal to the question variable you declared above. 
function loadQuestion(){
document.getElementById("questionText").innerHTML = question;
}

// Create a function called checkAnswer(userAnswer) that takes one incoming parameter. 
function checkAnswer(userAnswer){
  if(userAnswer===answer){
    document.getElementById("responseText").innerHTML = "That is correct!";             
    document.getElementById("responseText").className = "correctAnswer";
  }
  else if(userAnswer!==answer){       
    document.getElementById("responseText").innerHTML = "I'm sorry, that is    
     not correct.";
    document.getElementById("responseText").className = "incorrectAnswer";
  }
}
// ---> If your answer variable matches the incoming userAnswer parameter, write a success message in the element called responseText. 
// ---> If your answer variable does NOT match the userAnswer parameter, write a failure message in the element called responseText. 

// Create TRADITIONAL DOM EVENT HANDLERS for the "onclick" events for the three buttons.
var start = document.getElementById("startButton");
var truth = document.getElementById("trueButton");
var falsify = document.getElementById("falseButton");
// The Start button should trigger the loadQuestion method
start.onclick = loadQuestion;
// The True button should trigger the checkAnswer method with a value of "true"
truth.onclick = checkAnswer("true");
// The False button should trigger the checkAnswer method with a value of "false"
falsify.onclick = checkAnswer("false");

2 个答案:

答案 0 :(得分:1)

如果您要比较为三重等式===确保两侧的类型相同

答案 1 :(得分:0)

应该是

<...>.onclick = function() {
   checkAnswer("true");
}

而不是

<...>.onclick = checkAnswer("true");