开发者

basic javascript quiz [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 7 years ago.

Improve this question

I have been given this code as an example to create a basic JavaScript qu开发者_JS百科iz:

var Question = function(id, text, correct, incorrect) {
    this.id = id;
    this.text = text;
    this.correct = correct;
    this.isCorrectlyAnswered = false;
    this.all = incorrect;
    this.all.push(correct);
    this.all.sort(randomSort);
}

Question.prototype.write = function() {
    var qu = document.getElementById("questions");
    qu.innerHTML += "<p>"+this.text+"</p>";

    var questionList = "<ul class='questionlist'>";
    for (var i=0; i<this.all.length; i++) {
        if ( this.all[i] == this.correct ) {

            questionList += "<li><label onclick='right("+this.id+")'><input type='radio' name='"+this.id+"'>"+this.all[i]+"</input></label></li>";

        } else {

            questionList += "<li><label onclick='wrong("+this.id+")'><input type='radio' name='"+this.id+"'>"+this.all[i]+"</input></label></li>";
        }
    }
    questionList += "</ul>";
    qu.innerHTML += questionList;
}

I have been baffled by this. Can anyone help me break down the code into 'understandable' chunks?


The code defines a Javascript class used for object oriented programming. You can say

 var q = new Question(.......);

with suitable parameters, and call the function

 q.write();

You can read more about the (slightly odd) way OOP works i JS: http://mckoss.com/jscript/object.htm

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜