在新旧字符串中存储随机数

时间:2013-10-19 08:01:02

标签: javascript jquery

这很难解释;如果你无法理解我的问题,请在评论中问我。

请参阅以下代码。首先,我从数组生成随机文本,然后我有两个div元素:currentold div。我想要实现的是当第一次按下开始按钮时,任何随机文本都可以显示在currentold div中。当第二次按下开始按钮时,old divcurrent div中出现的任何文本都应显示在old中,并且任何随机文本都显示在旧div中并且循环继续。

我尝试将undefined初始化为0,但它在函数内显示为<script> function randomFromTo(from, to) { return Math.floor(Math.random() * (to - from + 1) + from); } var arrstring = new Array("images", "wallpaper", "photos", "vector", "designer", "wordpress", "jquery", "extjs", "scripting", "blogging", "search", "tagging", "digital", "javascript", "server", "hosting", "social", "twitter", "graphic", "photoshop", "netbeans", "mysql", "apache", "iphone", "mobile", "android", "framework", "usability", "optimization", "interface", "developer"); function random() { randomIndex = randomFromTo(0, arrstring.length - 1); return randomIndex; } var old = 0; function start() { var all = old; var old = random(); $(".current").text(arrstring[all]); $(".old").text(arrstring[old]); } </script> <div class="current">old</div> <div class="old">new</div> <input type="button" onclick="start();" value="start" />

{{1}}

5 个答案:

答案 0 :(得分:2)

我自己解决了问题,我刚刚删除了var,它成功地运作了

 function start()
    {
    all = old;
    old = random();
    $(".current").text(arrstring[all]);
    $(".old").text(arrstring[old]);

    }

答案 1 :(得分:2)

这将以更清洁的方式为您提供相同的功能,但不会污染全局范围。

jsFiddle

function get_Random_String() {

    var arrstring = new Array("images", "wallpaper", "photos", "vector",
        "designer", "wordpress", "jquery", "extjs", "scripting", "blogging",
        "search", "tagging", "digital", "javascript", "server", "hosting",
        "social", "twitter", "graphic", "photoshop", "netbeans", "mysql",
        "apache", "iphone", "mobile", "android", "framework", "usability",
        "optimization", "interface", "developer");

    return arrstring[Math.floor(Math.random() * arrstring.length)];

}

function cycle_randoms() {
    $(".current").text($(".old").text());
    $(".old").text(get_Random_String());
}


$('input[value=start]').on('click', function () {
    cycle_randoms();
});

答案 2 :(得分:1)

看起来你很亲密!只是遇到了variable scope个问题。尝试这样的事情:

function start() {
  var all = random();
  $(".current").text(arrstring[all]);
  $(".old").text(arrstring[old]);
  old = all;
}

http://jsfiddle.net/daCrosby/zbSDC/

答案 3 :(得分:0)

使用同名的全局变量和局部变量 只删除var到局部变量.. 它将赋予该函数不同的含义..

    var old = 1; // Global
    function start() {
    var all = old; //local
    var old = random(); //local..
    ..}

答案 4 :(得分:-1)

请使用jQuery内置程序。

在将更改应用于dom之前,您应该使用doc:

$(document).ready(function(){
       /*ALL JS CODE HERE.*/
    });

尝试使用jQuery事件监听器:

$("button").click(function(){
   /*here is 'start' function */
});

可选的: 将所有js代码放在code.js个文件中,并将它们放在头部。