在 javascript 中刷新浏览器时保留多个元素的背景颜色?

Keep Background Color for multiple elements when the browser is refershed in javascript?

我试图在刷新浏览器时保持不同元素的背景颜色相同 这是一个笔记网站项目,一个人可以添加任意数量的笔记,所以我想保存他们选择的颜色,每个元素(笔记)可以不同,然后刷新浏览器时颜色将保持不变。

这是“元素如何显示”的代码

function showNote2() {
    console.log("Show");
    let note = localStorage.getItem("notes");
    if(note == null){
        noteData = []
        // message.innerText = "Please Add a Note"
    }
    else{
        noteData = JSON.parse(note);
    };
    let showBox = "";
    noteData.forEach(function show(element, index) {
        showBox += `<div class="noteCard my-2 mx-2 card" id="cardID" style="width: 18rem;">
        <select id="mySelect${index}" class="clr-btn" style="text-align:center" onchange="changeColor(${index})">
        <option id="bckgrnd-clr" value="white">Background Color</option>
        <option  value="Red">Red</option>
        <option value="Green">Green</option>
        <option  value="Blue">Blue</option>
        </select>
                <div class="card-body" id="card${index}">
                  <h5 class="cardtitle">Note
                  ${index + 1}
                  </h5>
                  <p class="card-text"> 
                  ${element}
                  </p>
                  <button id="${index}" onclick="deleteNote(this.id)" class="btn btn-primary">Delete Note</a>
                </div>
              </div>  
            })

      let showNote3 = document.getElementById("notes2");
      if(noteData.length != 0){
          showNote3.innerHTML = showBox;
      }else{
          showNote3.innerHTML = "Please add a Note"
      }   
}`

这是用于应用颜色的函数:

function changeColor(index,e) {
    console.log("Change",e)
    let note = localStorage.getItem("notes");
    if(note != null ){
        let showNote3 = document.getElementById(`card4${index}`)
        console.log(showNote3)
        let colorApply = document.getElementById(`card${index}`)
        console.log(colorApply)
        let elm1 = document.getElementById(`mySelect${index}`)
        console.log(elm1)
        let color = elm1.options[elm1.selectedIndex].value;
        colorApply.style.backgroundColor = color;
        localStorage.setItem(`clr${index}`, color)
    }
    else{
        `Note is Empty`
    }

这是我用来存储和调用所选值的代码。 它在存储值时工作正常,但在返回时不起作用。

function backGroundClr(index) {
        let backclr2 = localStorage.getItem(`clr${index}`)
        colorApply.style.backgroundColor = backclr2   
        console.log(backGroundClr)    
}

谢谢

在循环中,在生成模板之前加载颜色。 然后在模板中使用

  noteData.forEach(function show(element, index) {

color = localStorage.getItem(`clr${index}`) || 'white'


showBox += `
       
<div class="card-body" id="card${index}" style="background-color:${color}">