0

我写了这段代码:

$(".awesome").click(function () {
        var toStore = $("input[name=name]").val();
        if (/^[A-Za-z]+ [A-Za-z]+$/.test(toStore)) {
            $("#contain").children().fadeOut(1000);
            $("#contain").delay(1000).queue(function () {
                $("#contain").append("<h1>Welcome to My Quiz : " + toStore + "</br>" +
                    "Youll Get 10 Questions To Answer </br> " +
                    "Here Is the First One:Who is Prime Minister of the United Kingdom? </h1>");

                var allQuestions = [
                    {question: "Who is Prime Minister of the United Kingdom?",
                        choices: ["David Cameron",
                            "Gordon Brown",
                            "Winston Churchill",
                            "Tony Blair"],
                        correctAnswer: 0}
                ];
                $("#contain").append("<form><input type='radio' name='ans1' value='David Cameron'>David Cameron</br>" +
                    " <input type='radio' name='ans1' value='Gordon Brown'>Gordon Brown</br>" +
                    "<input type='radio' name = 'ans1' value = 'Winston Churchill' > Winston Churchill </br>" +
                    "<input type='radio' name='ans1' value='Tony Blair'>Tony Blair</br>" +
                    "<input type='submit' value='Submit' name='submit'></form>");
                $("input[name=submit]").click(function () {
                    var correctAnswer;
                    if ($("input[name=ans1]").val()) {
                        var x = "choices";
                        allQuestions[x] = "David Cameron";
                        for (var x in allQuestions) {
                            return correctAmswer = false;

                            if (allQuestions[x] === "David Cameron") {

                                return correctAnswer = true;
                            } else {
                                return correctAnswer = false;
                            }

                        }
                    }
                });
            });
        } else {
            alert("You Must Put a Valid Name");
        }
    });
});

现在你可以看到我有一个名为“allQuestions”的对象。现在我有 3 个属性:“问题”“选择”和“正确答案”。之后我有一个提交按钮,如果你点击它,它会检查输入 name="ans1" 的值,然后我会遍历对象 "allQuestions" 中的所有选项;如果然后答案是“大卫卡梅隆”,我希望它将正确答案存储为 1 而不是 0;否则我不想存储正确答案,它仍然为 0,因为我之后有更多问题。有什么建议吗?

4

1 回答 1

1
  • 第一个问题是,如果在添加元素之前注册事件处理程序,则直接事件处理不适用于动态添加的元素。在您的情况下,我认为它有效,因为您在添加元素后注册了事件处理程序。但是您应该将其更改为:

    $("#contain").on("click","input[name=submit]", function(){ your function})

  • 第二个问题是您访问 allQuestions 的方式不正确,因为它是一个数组。应该是:allQuestions[0][x];

  • 像@Benjamin Gruenbaum 提到的第三个问题。

于 2013-04-07T05:44:58.000 回答