按钮只能在网站上工作一次,需要它无限次工作

Button only works once on a website, need it to work infinitely many times

我是编码初学者(如果这个问题有一个容易解决的解决方案,请原谅我),但我正在尝试创建一个颜色翻转器,每次将网页背景更改为随机颜色单击“生成”按钮。我不知道如何配置按钮,所以我查看了有关如何配置的教程。教程和我的版本的代码是一样的,但是我在网页上点击了一次“生成”之后,就再也没有改变背景了。下面是按钮的代码:

<main>
        <div class="container">
            <h1>color flipper</h1>
            <h2>press the button to generate a random color.</h2>
            <h3> color: <span class="color">#000000</span></h3>
            <button class="btn btn-hero" id="btn">generate</button>
        </div>   
</main> 
<script>
        const btn = document.getElementById("btn")
        const color = document.querySelector(".color")

        let a = Math.floor(Math.random() * 256)
        let b = Math.floor(Math.random() * 256)
        let c = Math.floor(Math.random() * 256)
        
        let colors = `rgb(${a}, ${b}, ${c})`

        btn.addEventListener('click',  () => {
            document.body.style.backgroundColor = colors
            color.textContent = colors
        })
</script>

随机颜色总是一样的,需要重新生成:

const btn = document.getElementById("btn")
const color = document.querySelector(".color")

function generate() {

    let a = Math.floor(Math.random() * 256)
    let b = Math.floor(Math.random() * 256)
    let c = Math.floor(Math.random() * 256)

    let colors = `rgb(${a}, ${b}, ${c})`
    document.body.style.backgroundColor = colors
    color.textContent = colors
}



btn.addEventListener('click',  () => {
    generate()
})
<main>
        <div class="container">
            <h1>color flipper</h1>
            <h2>press the button to generate a random color.</h2>
            <h3> color: <span class="color">#000000</span></h3>
            <button class="btn btn-hero" id="btn">generate</button>
        </div>   
</main> 

每当点击 btn 时,您需要确保每次都生成一种新颜色。您可以通过将颜色生成逻辑置于事件侦听器的回调中来完成此操作。

const btn = document.getElementById("btn")
const color = document.querySelector(".color")

btn.addEventListener('click',  () => {
    let a = Math.floor(Math.random() * 256)
    let b = Math.floor(Math.random() * 256)
    let c = Math.floor(Math.random() * 256)

    let colors = `rgb(${a}, ${b}, ${c})`
    
    document.body.style.backgroundColor = colors
    color.textContent = colors
})
<main>
  <div class="container">
      <h1>color flipper</h1>
      <h2>press the button to generate a random color.</h2>
      <h3> color: <span class="color">#000000</span></h3>
      <button class="btn btn-hero" id="btn">generate</button>
  </div>   
</main>