2

这个脚本给我带来了问题。我已经重写了好几次,但我错过了一些东西。

“问题”数组指的是我的对象。这些对象是不同的问题,“a”始终是正确答案。

到目前为止,该脚本工作正常。这个想法是从 0 增加“n”以滚动浏览我的数组,并在单击正确答案时提供下一个问题。'x' 总是正确的答案(它总是持有 'a')。

所以我可以在正确猜测时增加'n';但是,当我再次调用函数“a()”时(在我的警报“hi”部分之后),它会导致问题。我想增加 n,并调用 a() 以便得到下一个问题。然后我想将正确的猜测 (x) 放置在随机位置(即位置 0、1 或 2。)

感谢任何帮助。

var questions = [q0,q1,q2,q3,q4,q5,q6,q7];

var n = 0;

function a(){
var y;
var z;

var x = Math.floor((Math.random() * 3))
if(x == 0){y = 1; z = 2}else if(x == 1){y = 0; z = 2}else{y = 0; z = 1}

$("#question_holder").text(questions[n].q);

    $(".answer_holder").eq(x).text(questions[n].a);
    $(".answer_holder").eq(y).text(questions[n].b);
    $(".answer_holder").eq(z).text(questions[n].c);


    $(document).ready(function(){

        $(".answer_holder").eq(x).click(function(){
            alert("hi");
                        n++;
            a();

                     /*this area needs to get the next question by incrementing
                     n, then generate a different value to x, to place it
                     in a different position. which it does. however,
                     in subsequent questions, you can click the wrong answer as if
                     it's correct, ie not 'a' or 'x'.*/
        });
    });
};
4

2 回答 2

3

您的逻辑在这里有点奇怪..您尝试做的是每次 a() 运行时注册一个新的单击事件。我认为您想为所有元素注册一次单击事件answer_holder,并在事件处理程序中检查这是哪个元素并相应地处理它

请注意以下事项:

$(document).ready(function(){- 这个处理程序中定义的函数应该在你的页面加载后运行。我认为你不想在 a() 中使用它。它通常只在全局范围内使用(在所有函数之外)

$(".answer_holder").eq(x).click(function(){- 此事件处理程序根据x. 我建议您为 all 注册一个事件处理程序$(".answer_holder"),而不依赖于x(在全局范围内)。在该事件处理程序中(在函数中),您检查哪个元素触发了事件(使用$(this)- 它返回被单击的元素)

于 2013-02-03T11:13:27.097 回答
2

你有 $(document).ready() 在错误的地方。尝试这样的事情(警告:这是完全未经测试的):

function setupQuestion(n) {
    var x,y,z;

    x = Math.floor((Math.random() * 3))
    if(x == 0){y = 1; z = 2}else if(x == 1){y = 0; z = 2}else{y = 0; z = 1}

    $("#question_holder").text(questions[n].q);

    $(".answer_holder").eq(x).text(questions[n].a).data('answer', 'a');
    $(".answer_holder").eq(y).text(questions[n].b).data('answer', 'b');
    $(".answer_holder").eq(z).text(questions[n].c).data('answer', 'c');
}

$(document).ready(function() {
    var n = 0;
    $('.answer_holder').click(function() {
        if ($(this).data('answer') === 'a') { // Or whatever is the correct answer
            n++;
            if (n < questions.length) {
                setupQuestion(n);
            } else {
                // Do something else, the test is finished
            }
        }
        return false;
    });
    setupQuestion(n);
});

请注意,我不是在比较text()函数,而是比较data()函数。这是因为显示给用户的文本可能会以某种方式进行修饰,从而使比较变得困难。简单地使用答案索引“a”“b”或“c”会更清楚。

于 2013-02-03T11:16:51.883 回答