无法访问我作为字符串传递的 DOM。如何使用我在代码中定义的外部函数来做到这一点?

Unable to access the DOM which I passed as a string. How to do it by using external function as I defined in the code?

我想在“重要”中添加一个事件link,即当一个用户点击“重要”link时,相应的卡片颜色应该更改并保存在本地存储中,但是,当我访问我作为字符串传递的 DOM 文件时,我无法执行此操作。例如- 我无法访问函数 markNotes(index) 中的 document.getElementsByClassName("noteCard")。但同时 console.log("Color is not applied") 执行成功。如果我添加 document.body.style.backgroundColor = "lightblue"; 那么主体颜色也会相应改变,但我只想用 class “noteCard”更改卡片的背景颜色。我真的坚持了。

下面是我的HTML代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Magic Notes</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link rel="stylesheet" href="Customstyle.css">

</head>

<body>
    <nav class="navbar navbar-expand-lg navbar navbar-dark bg-dark">
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarTogglerDemo01">
            <a class="navbar-brand" href="#">Magic Notes</a>
            <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
                <li class="nav-item active">
                    <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="https://www.facebook.com/balabhadra.chand/" target="_blank">About me</a>
                </li>

            </ul>
            <form class="form-inline my-2 my-lg-0">
                <input class="form-control mr-sm-2" id="searchTitle" type="search" placeholder="Search by title" aria-label="Search">
            </form>
            <form class="form-inline my-2 my-lg-0">
                <input class="form-control mr-sm-2" id="searchTxt" type="search" placeholder="Search text" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0 " id="searchBtn" type="submit">Search</button>
            </form>
        </div>
    </nav>
    <h1 class="heading">It's all about magic !!!</h1>
    <div class="card" style="width: 1000px;">

        <div class="input-group">
            <div class="input-group-prepend">
                <span class="input-group-text">Add a title to your note</textarea></span>
            </div>
            <textarea class="form-control" id="addTitle" aria-label="With textarea"></textarea>
        </div>

        <div class="card-body">
            <form>
                <div class="form-group">
                    <label for="exampleFormControlTextarea1">Write your Note</label>
                    <textarea class="form-control" id="addTxt" rows="3"></textarea>
                </div>
            </form>

            <button class="btn btn-primary" id="addBtn">ADD NOTE</button>
        </div>

    </div>
    <hr>
    <h5>Your Notes</h5>
    <hr>
    <div id="notes" class="row container-fluid"></div>


    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
    <script src="myscript.js"></script>
</body>

这是我的JavaScript代码

console.log('MagicNotes')
showNotes();

let addBtn = document.getElementById("addBtn");
addBtn.addEventListener("click", function(e) {
    let addTxt = document.getElementById("addTxt");
    let addTitle = document.getElementById("addTitle");
    let notes = localStorage.getItem("notes");
    if (notes != null) {
        notesObj = JSON.parse(notes);
    } else {
        notesObj = [];
    }
    let myObj = {
        title: addTitle.value,
        text: addTxt.value
    }
    notesObj.push(myObj)
    localStorage.setItem("notes", JSON.stringify(notesObj));
    addTxt.value = "";
    addTitle.value = "";
    showNotes();
});

function showNotes() {
    let notes = localStorage.getItem("notes");
    if (notes != null) {
        notesObj = JSON.parse(notes);
    } else {
        notesObj = [];
    }
    let html = "";
    notesObj.forEach(function(element, index) {
        html += `<div class="noteCard card" style="width: 18rem;">
        <div class="card-body">
          <h5 class="card-title">Title: ${element.title}</h5>
          
          <p class="card-text">${element.text}</p>
          <a href="#" id="${index}"onclick="deleteNotes(this.id)" class="card-link" >Delete Note</a>
          <a href="#" id="${index}"onclick="markNotes(this.id)"class="card-link">Important</a>
        </div>
      </div>`;

    });
    let notesElem = document.getElementById("notes");
    if (notesObj.length != 0) {
        notesElem.innerHTML = html;
    } else {
        notesElem.innerHTML = `Please add a note by clicking "ADD NOTE"`;
    }
}

function deleteNotes(index) {
    let notes = localStorage.getItem("notes");
    if (notes != null) {
        notesObj = JSON.parse(notes);
    } else {
        notesObj = [];
    }
    notesObj.splice(index, 1);
    localStorage.setItem("notes", JSON.stringify(notesObj));
    showNotes();
}

function markNotes(index) {
    let notes = localStorage.getItem("notes");
    if (notes != null) {
        notesObj = JSON.parse(notes);
    } else {
        notesObj = [];
    }
    document.getElementsByClassName("noteCard").style.color = "lightblue";
    console.log("Color is not applied")
    localStorage.setItem("notes", JSON.stringify(notesObj));
    showNotes();
}

let searchText = document.getElementById('searchTxt');
searchText.addEventListener("input", function(txt) {

    let inputVal = searchText.value.toLowerCase();
    // console.log('Input event fired!', inputVal);
    let noteCards = document.getElementsByClassName('noteCard');
    Array.from(noteCards).forEach(function(element) {
        let cardTxt = element.getElementsByTagName("p")[0].innerText;
        if (cardTxt.includes(inputVal)) {
            element.style.display = "block";
        } else {
            element.style.display = "none";
        }
        // console.log(cardTxt);
    })
})
let searchTitle = document.getElementById('searchTitle');
searchTitle.addEventListener("input", function(title) {

    let inputValTitle = searchTitle.value.toLowerCase();
    let noteCardsTitle = document.getElementsByClassName('noteCard');
    Array.from(noteCardsTitle).forEach(function(element) {
        let cardTitle = element.getElementsByTagName("h5")[0].innerText;
        if (cardTitle.includes(inputValTitle)) {
            element.style.display = "block";
        } else {
            element.style.display = "none";
        }
        // console.log(cardTitle);
    })
})

您在 markNotes:

中获取元素时丢失了 index
function markNotes(index) {
   let notes = localStorage.getItem("notes");
   if (notes != null) {
    notesObj = JSON.parse(notes);
   } else {
    notesObj = [];
   }
  let noteCard = document.getElementsByClassName("noteCard")[index];
    noteCard.style.color = "lightblue";
    console.log("Color is applied")
   localStorage.setItem("notes", JSON.stringify(notesObj));
   //showNotes(); you don't need to add this again
}

完整的工作代码fiddlelink