社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Jquery

使用jQuery每4秒显示3种随机颜色

Peanuts • 5 年前 • 1670 次点击  

我有这个代码,我试图从一个数组中显示3种随机颜色, ,每4秒一次,但是我每4秒得到一种颜色,即使它们是随机的。。。

我错过了什么?

//set colors
var colors = ["white", "red", "blue", "yellow", "orange", "brown", "black", "violet", "purple", "pink", "green"];

//pick 3 of them randomly
var three_random_colors = (n) => {
    return colors.reduce((memo, val, index) => {
        var p = (n-memo.length); // How many remaining to choose.
        var q = colors.length-index; // How many remaining to choose from.
        if (Math.random() < p/q){
            memo.push(val);
        }
        return memo;
    }, []);
};

//output the colors on the HTML
var counter = 0; //start counter
var elem = document.getElementById("changeText");//the place where we change things
setInterval(change, 4000);//every 4 seconds run the following stuff:
function change() {
 var text = three_random_colors(3);//get what's inside "three_random_colors"
 elem.innerHTML = text[counter];//on div, add content <--- (I want 3 at once here! but I get only 1)
    counter++;
    if(counter >= text.length) { counter = 0; var text = three_random_colors(3); }//reset
}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54768
 
1670 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Nick
Reply   •   1 楼
Nick    5 年前

你的问题是 change

text.join(' ')

你会看到这三种颜色:

//set colors
var colors = ["white", "red", "blue", "yellow", "orange", "brown", "black", "violet", "purple", "pink", "green"];

//pick 3 of them randomly
var three_random_colors = (n) => {
  return colors.reduce((memo, val, index) => {
    var p = (n - memo.length); // How many remaining to choose.
    var q = colors.length - index; // How many remaining to choose from.
    if (Math.random() < p / q) {
      memo.push(val);
    }
    return memo;
  }, []);
};

//output the colors on the HTML
var elem = document.getElementById("changeText"); //the place where we change things
setInterval(change, 4000); //every 4 seconds run the following stuff:
function change() {
  var text = three_random_colors(3); //get what's inside "three_random_colors"
  elem.innerHTML = text.join(' '); //on div, add content <--- (I want 3 at once here! but I get only 1)
}
<div id="changeText"></div>