用javascript停止随机字母

时间:2012-04-21 20:12:20

标签: javascript html random

这里我有一个代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Letters</title>
</head>

<body>
<div id="stop">STOP</div>

<div id="letter">A</div>
<div id="letter">G</div>
<div id="letter">D</div>
<div id="letter">M</div>
<div id="letter">S</div>
<script type="text/javascript">
var letters = ['a','b','c','d', ... ];
var getRandLetter = function () {
    return letters[ Math.random() * 25 ] //generate a random number between 0 and 25, use this to pick a letter
}
setInterval($('#letter').text(getRandLetter()), 500) //pop a random letter in the DOM every 500 ms
</script>

</body>
</html>

使用脚本我需要每隔0.5秒更改div上的字母,但是 -

当我点击STOP div时,我需要:第一个div - “A”第二个div“B”......等我怎么能这样做。请帮忙!有没有机会这样做!

2 个答案:

答案 0 :(得分:0)

即使你可能不应该给你的div与上面提到的相同的id,这实际上可以工作(显然没有测试):

var curIdx = 0;
//choose a new first letter index every 500 ms
var interval = setInterval(function(){curIdx = Math.random() * 25;}, 500);

$('#stop').click(function(){
    var allDivs = $('#letter');
    for( var i = 0; i < letters.length; i++ )
    { 
       var offset = (curIdx + i) % letters.length;
       allDivs[i].text(letters[offset]);
    }
    //edit: to stop the thing from running
    clearInterval(interval);
}

this is assuming, you have as many divs as letters...

edit: i made a fiddle yesterday, that i forgot to post: [http://jsfiddle.net/qpg4V/8/][1]

答案 1 :(得分:0)

<div id="s">STOP</div>
<div id="L1"></div>
<div id="L2"></div>
<div id="L3"></div>
<div id="L4"></div>
<div id="L5"></div>

v=setInterval(function(){for(i=0;i<6;i++){$("#L"+i).html(String.fromCharCode(Math.floor(Math.random()*26+65)))};},500);
$("#s").click(function(){clearInterval(v);});

http://jsfiddle.net/Hx28c/1/

享受你的游戏。