2

Sorry if this a duplicate Question, searched high and low and could not find an answer.

I'm trying to generate a new random number on every click. So far, only the first number is random and on every subsequent click nothing happens. I think the getRandomNumber function is only evaluated once and thats why i'm getting the same number.

$(document).ready(function(){    
    var index = 0; 

    function getRandomNumber(){
        shuffle = function(o){
            for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
                return o;
        };

        var randorder = shuffle([0,1,2,3,4]);

        return randorder[index++];
    }

    $("#button2").click(function(){
        var gameq = new Array();
        gameq[0] = "Question 1 ?";
        gameq[1] = "Question 2 ?";
        gameq[2] = "Question 3 ?";
        gameq[3] = "Question 4 ?";
        gameq[4] = "Question 5 ?";

        $("#question").replaceWith('<h5>' + gameq[getRandomNumber()] + '</h5>')
    });
});
4

1 回答 1

5

你只是#question第一次杀死你的元素。尝试像这样更改最后一行:

$("#question").replaceWith('<h5 id="question">' + gameq[getRandomNumber()] + '</h5>');

或者它对你也有好处:

$("#question").html('<h5>' + gameq[getRandomNumber()] + '</h5>');
于 2013-07-01T09:36:16.707 回答