2013-10-19 131 views
2

這很難解釋;如果你不明白我的問題,請在評論中問我。在舊字符串和新字符串中存儲隨機數

請參閱下面的代碼。首先,我從一個數組中生成隨機文本,然後我有兩個div元素:currentold div。我想實現的是當第一次按下開始按鈕時,任何隨機文本都可以在currentold div中顯示。當第二次按下開始按鈕時,無論哪個文本出現在old div第一次應顯示在current div和任何隨機文本顯示在舊的div和循環繼續。

我試圖用0初始化old,但它顯示爲undefined裏面的函數。

<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" /> 

回答

2

嗨,大家好解決的問題我自己,我只是刪除var和它成功運行

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

    } 
-1

請使用jQuery的內置程序。

你應該使用文檔準備將更改應用到DOM前:

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

嘗試使用jQuery的事件偵聽器:

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

可選: 都放在code.js文件JS代碼,並把它們在你的頭部內。

+0

嘿多數民衆贊成在乾淨感謝信息:) – Vishnu

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(); 
}); 
+0

這是整潔的謝謝+1 :) – Vishnu

+0

不客氣! –

0

具有相同名稱的全局和局部變量的使用.. 只能去除VAR局部變量.. 它會給該函數內部不同含義..

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