我需要在div中显示随机单词而不重复单词。 随机单词将在每个随机秒(3-5秒)附加一个div。 如果数组中的所有值都显示在div中,则会发出警报。
例:
b a c d ALERT('DONE')
不:
b a b c d d a a c
我的代码:
$(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(""+thisWord+""); 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 $('') .text(word) .appendTo('#container'); var delay = Math.round(Math.random() * (3000 - 500)) + 500; setTimeout(appendIfMore, delay); }; // start appending stuff appendIfMore(); });
JSBIN
以上就是jQuery教程分享Jquery随机单词不重复相关内容,想了解更多jQuery开发(异常处理)及jQuery教程关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/jquerytutorial/569944.html
赞 (0)
少年三国志搞笑英文免费精选名字大全分享
上一篇
2021年2月26日
jQuery技术:使用jQuery AJAX调用PHP函数
下一篇
2021年2月26日