css 加载脚本后立即显示数组中的随机项,并将示例保存在另一个数组中

gk7wooem  于 2023-02-10  发布在  其他
关注(0)|答案(2)|浏览(88)

在我的代码中,我需要用不同的颜色显示一些随机的动物名称,当按下键盘上的某个键时,它们都会改变,然后保存它们的显示顺序。我的问题是,第一个随机颜色的动物名称只有在我按下键盘上的“r”或“t”键后才显示,而不是在脚本启动时立即显示。我尝试过在事件侦听器函数之外添加它们。但是这样我就不能把它们保存在saveData数组中了,我想避免在没有必要的情况下添加代码来保存第一个示例。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="style.css">
    <title></title>
</head>
<body>
    <section>
        <div class="animals" id="animals"></div>
    </section>

    <script src="script.js" defer></script>
</body>
</html>

显示如下:

const showAnimal = () => {
    const animals = {"dog": "yellow", "cat":"black", "fish":"blue","mouse":"gray"};
    const colors = Object.keys(animals);
    const name = Object.values(animals);

    const numOfAnimals = 15; 
    let num = 0;    
    var saveData = []

    const selectRandomFeature = (name, colors) => {
        const randomTextIndex = Math.floor(Math.random() * name.length);   
        const randomColorIndex = Math.floor(Math.random() * colors.length); 

        var randomText = name[randomTextIndex];  
        const randomColor = colors[randomColorIndex];

        return [randomText, randomColor, randomTextIndex, randomColorIndex];
    }

    const displayAnimals = (randomText, randomColor, randomTextIndex , randomColorIndex) => {
        if (num < numOfAnimals - 1) {        
            document.getElementById("animals").innerText  = `${randomColor}`;   
            document.getElementById("animals").style.color = randomText;

            console.log(randomColor);
            console.log(randomText);
        } else {
            console.log(saveData)
        }
    }

    document.addEventListener('keydown', (event) => {
        const [randomText, randomColor, randomTextIndex , randomColorIndex] = selectRandomFeature(name, colors);

        if (event.key === 'r') {            
            if (randomTextIndex == randomColorIndex) {
                saveData.push({"text": randomText, "color": randomColor, "direction":"left"})
            } else {
                saveData.push({"text": randomText, "color": randomColor, "direction":"left"})
            }          
            displayAnimals(randomText, randomColor, randomTextIndex , randomColorIndex);  
            num++;   
        } else if (event.key === 't') { 

            if (randomTextIndex == randomColorIndex) {
                saveData.push({"text": randomText, "color": randomColor, "direction":"righ"})
            } else {
                saveData.push({"text": randomText, "color": randomColor, "direction":"right"})
            }   
            displayAnimals(randomText, randomColor, randomTextIndex , randomColorIndex);         
            num++;                        
        }        
    });
}  
showAnimal()

如何在脚本启动后立即以随机颜色显示随机名称,并确保将其保存在saveData数组中,与单击键盘键时出现的以下名称放在一起?

1cosmwyk

1cosmwyk1#

你好我也许找到了一个解决方案,你可以试试
1.首先我把你所有的代码从showAnimals函数中取出
1.然后我把代码拆分成不同的函数,使其更具可读性
1.删除一些逻辑相同的重复代码
1.最后,我创建了一个函数,在eventListener中实现您的逻辑,并在页面加载时调用它addAnimal(direction)

//Puts everything out of showAnimal()
const animals = { dog: "yellow", cat: "black", fish: "blue", mouse: "gray" };
const colors = Object.keys(animals);
const name = Object.values(animals);

const numOfAnimals = 15;
let num = 0;

//As a global variable, it's accessible everywhere in the scope
var saveData = [];

const displayAnimals = (
  randomText,
  randomColor
  //Remove two unnecassary parameters (randomTextIndex , randomColorIndex)
) => {
  if (num < numOfAnimals - 1) {
    document.getElementById("animals").innerText = `${randomColor}`;
    document.getElementById("animals").style.color = randomText;

    console.log(randomColor);
    console.log(randomText);
  } else {
    console.log(saveData);
  }
};

const selectRandomFeature = (name, colors) => {
  const randomTextIndex = Math.floor(Math.random() * name.length);
  const randomColorIndex = Math.floor(Math.random() * colors.length);

  var randomText = name[randomTextIndex];
  const randomColor = colors[randomColorIndex];

  return [randomText, randomColor, randomTextIndex, randomColorIndex];
};

//Direction can be 'left' or 'right'
const addAnimal = (direction) => {
  const [randomText, randomColor, randomTextIndex, randomColorIndex] =
    selectRandomFeature(name, colors);

  saveData.push({
    text: randomText,
    color: randomColor,
    direction: direction,
  });

  displayAnimals(randomText, randomColor, randomTextIndex, randomColorIndex);

  num++;
};

/*
    In your event listener you have some duplication code
    If condition (randomTextIndex == randomColorIndex) is true or not your doing the same logic
    Also you execute displayAnimals(randomText, randomColor, randomTextIndex , randomColorIndex`; and num++; even if your keydown it's 'r' or 't'
*/
document.addEventListener("keydown", (event) => {
  if (event.key === "r" || event.key == "t") {
    //Ternary operator condition if value else otherValue
    const direction = event.key == "r" ? "left" : "right"; 
    addAnimal(direction);
  }
});

//Call for the first time
addAnimal("right");

希望这个解决方案对你有帮助🧙‍♂️。

yftpprvb

yftpprvb2#

当页面加载时,它没有加载,因为该函数仅在eventListener上调用。您可以在eventListener之前调用该函数,并将值保存在数组中。另外,在代码的第49行,您在direction:right处缺少了一个“t”。以下是我更改的代码。请让我知道您对它的看法。

const displayAnimals = (randomText, randomColor, randomTextIndex , randomColorIndex) => {
        if (num < numOfAnimals - 1) {        
            document.getElementById("animals").innerText  = `${randomColor}`;   
            document.getElementById("animals").style.color = randomText;

            console.log(randomColor);
            console.log(randomText);
        } else {
            console.log(saveData)
        }
    }

    const [randomText, randomColor, randomTextIndex , randomColorIndex] = selectRandomFeature(name, colors);

    saveData.push({"text": randomText, "color": randomColor, "direction": randomColorIndex})
    // call function here so it shows when script loads
    displayAnimals(randomText, randomColor, randomTextIndex, randomColorIndex);

    document.addEventListener('keydown', (event) => {
        const [randomText, randomColor, randomTextIndex , randomColorIndex] = selectRandomFeature(name, colors);

        if (event.key === 'r') {            
            if (randomTextIndex == randomColorIndex) {
                saveData.push({"text": randomText, "color": randomColor, "direction":"left"})
            } else {
                saveData.push({"text": randomText, "color": randomColor, "direction":"left"})
            }          
            displayAnimals(randomText, randomColor, randomTextIndex , randomColorIndex);  
            num++;   
        } else if (event.key === 't') { 

            if (randomTextIndex == randomColorIndex) {
                saveData.push({"text": randomText, "color": randomColor, "direction":"right"})
            } else {
                saveData.push({"text": randomText, "color": randomColor, "direction":"right"})
            }   
            displayAnimals(randomText, randomColor, randomTextIndex , randomColorIndex);         
            num++;                        
        }        
    });
}  
showAnimal()

相关问题