如何更改 Javascript 中列表的字体颜色?

How to change the font color of a list in Javascript?

所以,我试图让我的这些导航链接在我点击按钮时改变它的颜色,但它似乎不起作用。

   <ul class="nav-links">
         <li id = link><a href="#">Home</a></li>
         <li id = link><a href="#">Projects</a></li>
         <li id = link><a href="#">About</a></li>
         <li id = link><a href="#">Contacts</a></li>
   </ul>
   <label class="toggle">
         <input type="checkbox" class="check">
         <span class="slider" onclick="dark()"></span>
   </label>

我尝试执行此脚本,但它仍然不起作用

  const text = document.querySelector(".logo");
  const body = document.querySelector("body");
  const banner = document.querySelector(".L-banner");
  const navLinks = document.getElementById("#link");
  function dark(){
      text.style.color = "#fff";
      body.style.background = "#000";
      banner.style.color = "#fff";

      for(var i = 0; i < navLinks.length; i++){
        navLinks[i].style.color = "#fffff";
      }
  }

您不能为多个元素指定相同的 ID,并且 querySelector 只能 select 一个元素。

到select所有链接,可以使用querySelectorAll

document.getElementById('button').addEventListener('click', changeColor);
function changeColor() {
    const links = [...document.querySelectorAll('.nav-links li a')];
    links.forEach(link => link.style.color = "cornflowerblue");
}
<ul class="nav-links">
    <li>
        <a href="#">Home</a>
    </li>
    <li>
        <a href="#">Projects</a>
    </li>
    <li>
        <a href="#">About</a>
    </li>
    <li>
        <a href="#">Contacts</a>
    </li>
</ul>
<button id="button">Change link color</button>

你应该改成这个

      const navLinks = document.querySelectorAll("#link a");

也别忘了修复html

<ul class="nav-links">
      <li id="link"><a href="#">Home</a></li>
      <li id="link"><a href="#">Projects</a></li>
      <li id="link" ink><a href="#">About</a></li>
      <li id="link" ink><a href="#">Contacts</a></li>
    </ul>