【问题标题】:Trying to change an element's color with JavaScript and I get Undefined error尝试使用 JavaScript 更改元素的颜色,但出现未定义错误
【发布时间】:2020-04-17 21:48:08
【问题描述】:

如果这听起来很愚蠢,我很抱歉,但是在 3 小时试图找到答案后,我不知所措。我刚开始为一个大学项目学习 Javascript。

所以我尝试使用 Javascript 动态更改页面中某些元素的颜色,虽然这适用于页脚等唯一元素,但我在元素中收到“未捕获的类型错误:无法读取未定义的属性‘样式’”例如 p 或 h4。我遵循了我在这个线程上读到的内容:How to set the color of H1 using javascript? 但我仍然收到错误消息。这是我的代码:

    const lightButton = document.getElementById("lighting_button");
console.log(lightButton);
const paragraph = document.querySelectorAll("p");
//console.log(p);

//console.log(contentHeader);
const bodyOfFile = document.body;

lightButton.addEventListener('click', (e) => {
  if(lightButton.textContent === "Dark Mode"){
    document.body.style.backgroundColor = "#1a1a1a";

    document.querySelector('#footer').style.color = "#e6e6e6";

    const contentHeader = document.querySelectorAll("h4");

    for(let j=0; contentHeader.length-1; j++){
      contentHeader[j].style.color = "#ffffff";
    }

    for(let i=0; paragraph.length-1; i++){
      paragraph[i].style.color = "#e6e6e6";
    }
  }

});

最奇怪的是,即使出现错误,它也确实使我的 h4 变白。 任何帮助将不胜感激。

【问题讨论】:

    标签: javascript css dom-events


    【解决方案1】:

    快速浏览了您的代码,如果我没记错的话,您的循环语法不正确尝试在两个循环中替换 for(let j=0; j<contentHeader.length;j++ for 循环中的中间语句不正确,它应该是一个返回 true 的条件,在您的情况下,它只是尝试 i=contentHeader.length-1

    【讨论】:

    • 天哪,你说的太对了!没想到检查它,因为它在抛出错误之前改变了所有元素的颜色,所以我很困惑!非常感谢!
    • 很高兴能帮上忙!请把我的答案标记为正确?
    【解决方案2】:

    你的 for 循环中有一个错字:

    const lightButton = document.getElementById("lighting_button");
    //console.log(lightButton);
    const paragraph = document.querySelectorAll("p");
    //console.log(p);
    //console.log(contentHeader);
    const bodyOfFile = document.body;
    lightButton.addEventListener('click', (e) => {
      if(lightButton.textContent === "Dark Mode"){
        document.body.style.backgroundColor = "#1a1a1a";
       
            document.querySelector('#footer').style.color = "#e6e6e6";
        
            const contentHeader = document.querySelectorAll("h4");
        
            for(let j=0; j < contentHeader.length-1; j++){
              contentHeader[j].style.color = "#ffffff";
            }
        
            for(let i=0; i < paragraph.length-1; i++){
              paragraph[i].style.color = "#e6e6e6";
            }
          }
        
        });
    <button id="lighting_button">Dark Mode</button>
    <h4>Title 1 </h4>
    <h4>Title 2 </h4>
    <h4>Title 3 </h4>
    <h4>Title 4 </h4>
    <h4>Title 5 </h4>
    <div id="footer">Footer</div>

    【讨论】:

      猜你喜欢
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      • 2020-12-07
      相关资源
      最近更新 更多