繁体   English   中英

尝试使用 JavaScript 更改元素的颜色,我得到未定义的错误

[英]Trying to change an element's color with JavaScript and I get Undefined error

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

因此,我尝试使用 Javascript 动态更改页面中某些元素的颜色,虽然这适用于页脚等唯一元素,但在 p 等元素中出现“Uncaught TypeError: Cannot read property 'style' of undefined”或 h4。 我按照我在这个线程上读到的内容: 如何使用 javascript 设置 H1 的颜色? 但我仍然收到错误消息。 这是我的代码:

    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 变白。 任何帮助将非常感激。

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

你的 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM