【问题标题】:Button to change background color更改背景颜色的按钮
【发布时间】:2021-06-22 19:59:41
【问题描述】:

我编写了这个短代码来显示一个将背景颜色更改为蓝色的按钮。在我点击按钮之前背景颜色会改变,我只是不知道为什么,在我点击按钮之前背景不应该默认为白色吗?

//function to change background color
function changeBg(color) {
    document.body.style.backgroundColor = color;
}

// goBlue closure
var goBlue = changeBg("blue");

// create button
var blueButton = document.createElement("button");
blueButton.innerHTML = "Blue";

// add button to page
var body = document.getElementsByTagName("body")[0];
body.appendChild(blueButton);

//add event listener
blueButton.addEventListener("click", goBlue);

感谢您的帮助

【问题讨论】:

  • 与您的帖子有些无关,但您应该停止使用“var”并使用“let”。我看不出 var 的意义是什么,考虑到变量具有全局范围,并且您的代码与根本不输入“var”是一样的。 “let”更好,因为它创建了一个“块范围的局部变量”

标签: javascript background-color


【解决方案1】:

var goBlue = changeBg("blue"); 将立即调用背景颜色更改。

相反,尝试将 changeBg 传递给事件监听器中的匿名函数

function changeBg(color) {
  document.body.style.backgroundColor = color;
}

// create button
var blueButton = document.createElement("button");
blueButton.innerHTML = "Blue";

// add button to page
var body = document.getElementsByTagName("body")[0];
body.appendChild(blueButton);

blueButton.addEventListener("click", () => {
  changeBg("blue")
});

【讨论】:

    【解决方案2】:

    这是因为您调用了函数changeBg,并且您将函数changeBg 的返回值(未定义)分配给goBlue 变量。

    var goBlue = changeBg("blue");
    

    如果您想在单击按钮时更改颜色,则需要添加addEventListener

    //function to change background color
    function changeBg(color) {
      document.body.style.backgroundColor = color;
    }
    
    // create button
    var blueButton = document.createElement("button");
    blueButton.textContent = "Blue";
    
    // add button to page
    var body = document.getElementsByTagName("body")[0];
    body.appendChild(blueButton);
    
    //add event listener
    blueButton.addEventListener("click", () => {
      changeBg("blue");
    });

    【讨论】:

      【解决方案3】:

      那是因为你在第 7 行调用了函数!

      var whatever = changeBg("blue") // <<<< Bam! BG is now blue
      // and the value of whatever is undefined since the function is void
      

      你想要的也许是:

      const EL_body = document.querySelector("body");
      const EL_btn = document.createElement("button");
      const changeBodyBg = (color) => EL_body.style.backgroundColor = color;
      
      EL_body.append(EL_btn);
      EL_btn.innerHTML = "Blue";
      EL_btn.addEventListener("click", () => changeBodyBg("blue"));

      上面只是为了简单起见,我使用了更好的函数命名和 Arrow Functions 的不同语法,你会得到这样的编辑:

      // REMOVE LINE 7 and...
      
      blueButton.addEventListener("click", function() {
        changeBg("blue")
      });
      

      【讨论】:

      • 谢谢!这行得通,但我只是想用闭包来设置它——如果不清楚的话,抱歉!我刚刚再试了一次,它不起作用的原因是因为函数需要这个返回的东西:return function() { document.body.style.backgroundColor = color; };我正在使用这个指南:developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
      • 只是补充一下,谢谢!函数语法肯定看起来更实用..