I'm making a quiz game in HTML/JavaScript which selects questions at random and adds the question and answer to the page ( document.getElementById, innerHTML
etc.)
I want to add a click listener so when an answer is clicked it will determine if it is correct or not. How should I set up this listener (or listeners?) to distinguish between li
s.
JavaScript
var elementQuestion = document.getElementById("question");
var elementAnswers = document.getElementById("answers");
elementQuestion.innerHTML = question[currentQuestion];
for(a = 0; a < answers[currentQuestion].length; a++) {
var li = document.createElement("li");
li.innerHTML = answers[currentQuestion][a];
elementAnswers.appendChild(li);
}
HTML
<!-- Question -->
<p id="question"> </p>
<!-- Answer Array -->
<ul id="answers"> </ul>
(I get the feeling I'm missing something obvious...) Thanks
When you add your answer, you can also add an EventListener for that:
elementAnswers.addEventListener("click", been_clicked, true);
In the callback funktion "been_clicked" you can refer to the Element that handled the Event (here: the ul-node) as "this", and to the Element that was clicked as "e.target":
function been_clicked(e) {
alert("You clicked '" + e.target.innerHTML + "'");
}
See http://jsfiddle.net/bjelline/7kSw5/ for a working demo.
Insert this into the loop:
li.onclick=create_on_click_function(li);
And add a new function, that will generate onclick callback function:
function create_on_click_function(element){
return function(){
alert(element.innerHTML + ' clicked');
}
}
Add appropriate parameters to determine, whether the id of the clicked <li>
element is equal to answer id.
If you add an id to each <li>
(like answer_0, answer_1, etc.), you can have a single listener on the <ul>
, to since events on the list items will bubble up:
var elementQuestion = document.getElementById("question");
var elementAnswers = document.getElementById("answers");
elementQuestion.innerHTML = question[currentQuestion];
for(a = 0; a < answers[currentQuestion].length; a++) {
var li = document.createElement("li");
li.innerHTML = answers[currentQuestion][a];
li.id = "answer_" + a
elementAnswers.appendChild(li);
}
elementAnswers.addEventListener("click", function(e) {
alert("Clicked on " + e.target.id);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.