button.value = "Submit";
button.id = "submit";
form.appendChild(button);
scoreDiv = document.createElement("div");
wsDiv.appendChild(scoreDiv);
//...
Note that the code we’ve written so far is already operation al in the sense that it will
produce a worksheet of ve equations and even allow the user to enter solutio ns. You
can try it if y ou like, just don’t forget to type the clo sin g curly bracket of the onload
handler. I haven’t typed it because we’re not finished with the handler yet.
Let’s now breathe some life into our generator by making it responsive to user clicks.
We’re going to do this by mea ns of the onclick h andler of the submit button. The
handler will compare the submitted answers with the correct solutions and display the
score each time the user clicks the button. The code is amazin gly simple:
//...
button.onclick = function() {
var i, score = 0;
for (i = 0; i < answers.length; i++) {
if (answers[i].dataset.solution ==
parseInt(answers[i].value)) {
score++; //Counts correct answers
}
}
scoreDiv.innerHTML = "You scored " +
score + " out of " + i + ".";
}; //Closing brace of the onclick handler
}; //Closing brace of the onload handler
Note that the arr ay answers is accessible inside the onclick event handler because
it is defined within its closure and stays available so long as the page is loaded in
the browser. To check the an swers it is only necessary to co mpare the properties
dataset.solution, and value of each of the Element objects stored in answers.
Finally, this is how o ur completed generator works:
254 Meeting 13. User Interface
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.249.210