我需要在 div 中显示随机单词而不重复该单词。随机单词将每隔随机秒(3-5 秒)附加一个 div。如果数组中的所有值都显示在 div 中,则会发出警报。
例子:
b
a
c
d
ALERT('DONE')
Not:
b
a
b
c
d
d
a
a
c
MY code:
$(document).ready(function($) {
words = ['a','b','c','d'];
function doSomething() {}
(function loop() {
var rand = Math.round(Math.random() * (3000 - 500)) + 500;
setTimeout(function() {
var thisWord = words[Math.floor(Math.random() * words.length)];
$("#container").append("<div class=\"conversation\">"+thisWord+"<div class=\"conversation\">");
doSomething();
loop();
}, rand);
}());
});
这是一个可行的解决方案:
$(document).ready(function() {
var words = ['a', 'b', 'c', 'd'];
var getRandom = function() {
var idx = Math.floor(Math.random() * words.length);
// grabs word and removes it from the array
return words.splice(idx, 1)[0];
};
var appendIfMore = function() {
var word = getRandom();
if (!word) return; // all done
$('<div class="conversation"/>')
.text(word)
.appendTo('#container');
var delay = Math.round(Math.random() * (3000 - 500)) + 500;
setTimeout(appendIfMore, delay);
};
// start appending stuff
appendIfMore();
});
JSBIN http://jsbin.com/zogibujutiya/1/edit
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)