简体   繁体   English

产生相同的随机数onclick

[英]Generating same random number onclick

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. 我认为getRandomNumber函数仅被评估一次,这就是为什么我得到相同的数字。

$(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>')
    });
});

You simply killing your #question element at first time. 您只需在第一时间杀死您的#question元素。 Try to change the last line like this: 尝试像这样更改最后一行:

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

Or may be it will be also good for you: 也许对您也有好处:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM