HTML Div 当我第二次访问它时元素变为空?

HTML Div Element turns to null when I'm accessing it a 2nd time?

以下是客户端代码的相关部分:

function simpsonsShow(forest) {

    alert(document.getElementById("simpsons"));
    var ind = simpsonsIndex(forest).toFixed(2); // simpsonsIndex is a function not shown here
    document.getElementById("simpsons").innerHTML = "";
    document.getElementById("simpsons").innerHTML = 
    document.getElementById("simpsons").innerHTML + ind;
}

document.addEventListener("DOMContentLoaded", function () {

    document.querySelector("div#intro button").addEventListener("click", function clicked() {

        document.getElementById("intro").style.display = "none";
        document.getElementById("sim").style.display = "block";
        document.getElementById("simpsons").style.display = "block";

        let content = document.getElementById("inputForest").value;
        let forest = forestGenerate(content);

        const ind = simpsonsShow(forest);

        let button = document.createElement("button");
        button.appendChild(document.createTextNode("generate"));
        button.addEventListener("click", function () {

            forest = forestGenerate(content);

            simpsonsShow(forest);
        });
        document.getElementById("sim").appendChild(button);
    });
});

当 simpsonsShow 函数第二次 运行 时,突然 document.getElementById("simpsons") 变为空,即使在第一次尝试时,它是一个正确的 HTML Div 元素.

以下是 HTML 的相关部分:

 <head>
     <script src="sim.js"></script>
 </head>

 <body>
     <div id="content">
         <div id="intro">
         </div>
         <div id="sim" class="hidden">
                <h2>the current Simpson's Index is: 
                </h2>
                <div id="simpsons">
                </div>
         </div>
     </div><!--close id="content"-->
 </body>
 </html>

我添加了代码片段:该网站通过按生成,然后不断按生成来工作。第二次按下生成时会弹出错误

function forestGenerate(content) {
    const forest = [];
    if (content.length === 0) {
        const possible = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""];
        for (let i = 0; i < 8; i++) {
            let text = '';
            for (let i = 0; i < 8; i++) {
                text += possible[Math.floor(Math.random() * possible.length)];
            }
            forest.push(text);
        }
    }
    else {
        const possible = [...content, ""];
        for (let i = 0; i < 8; i++) {
            let text = '';
            for (let i = 0; i < 8; i++) {
                text += possible[Math.floor(Math.random() * possible.length)];
            }
            forest.push(text);
        }
    }

    for (let i = 0; i < forest.length; i++) {
        let row = document.createElement("div");
        let newContent = document.createTextNode(forest[i]);
        row.appendChild(newContent);
        row.addEventListener("click", function () {
            row.style.backgroundColor = "grey";
            row.setAttribute("pinned", "yes");
        });

        document.getElementById("sim").appendChild(row);
    }
    return forest;
}

function simpsonsShow(forest) {
    const simpsonsIndex = forest =>
    1 - Object.entries(
        [...forest.join("")].reduce(
            (counts, emoji) => ({ ...counts, [emoji]: (counts[emoji] || 0) + 1 }),
            {}
        )
    ).reduce(([top, bottom], [species, count]) => [top + (count * (count - 1)), bottom + count], [0, 0])
        .reduce((sumLilN, bigN) => sumLilN / (bigN * (bigN - 1)))

    alert(document.getElementById("simpsons"));
    var ind = simpsonsIndex(forest).toFixed(2);
    document.getElementById("simpsons").innerHTML = "";
    document.getElementById("simpsons").innerHTML = document.getElementById("simpsons").innerHTML + ind;
}

document.addEventListener("DOMContentLoaded", function () {

    let element = document.getElementById("sim");
    element.classList.add("hidden");

    let element1 = document.getElementById("pushtray");
    element1.classList.add("hidden");

    document.querySelector("div#intro button").addEventListener("click", function clicked() {

        document.getElementById("intro").style.display = "none";
        document.getElementById("sim").style.display = "block";
        document.getElementById("simpsons").style.display = "block";

        let content = document.getElementById("inputForest").value;
        let forest = forestGenerate(content);

        const ind = simpsonsShow(forest);

        if (ind <= .7) {
            let over = document.createElement("div");
            let newContent = document.createTextNode("WARNING: Simpson's Index Dropped To" + simpsonsIndex);
            over.appendChild(newContent);
            document.getElementById("pushtray").appendChild(over);
            document.getElementById("pushtray").style.zIndex = "100";
            document.getElementById("pushtray").style.right = "50px";
            document.getElementById("pushtray").style.position = "fixed";
            document.getElementById("pushtray").style.display = "block";
        }

        let button = document.createElement("button");
        button.appendChild(document.createTextNode("generate"));
        button.addEventListener("click", function () {
            
            const curr = document.getElementById("sim").querySelectorAll("div");
            for (let i = 0; i < curr.length; i++) {
                if (!curr[i].hasAttribute("pinned")) {
                    document.getElementById("sim").removeChild(curr[i]);
                }
            }

            document.getElementById("sim").removeChild(button);

            forest = forestGenerate(content);

            simpsonsShow(forest);

            document.getElementById("sim").appendChild(button);
        });
        document.getElementById("sim").appendChild(button);
    });
});
     <!doctype html>
     <html>

     <head>
         <title>FOREST SIMULATOR</title>
         <script src="sim.js"></script>
         <link rel="stylesheet" href="base.css" type="text/css" media="screen" title="no title" charset="utf-8">
       <link href="https://fonts.googleapis.com/css?family=Lato|Playfair+Display" rel="stylesheet" >

     </head>

     <link href="https://fonts.googleapis.com/css?family=Lato|Playfair+Display" rel="stylesheet">

     <body>
         <div id="content">
             <h1>FOREST SIMULATOR</h1>
             <style>
                    .hidden{
                      display:none;
                    }
            </style>
             <div id="intro">
                 starting forest (leave empty to randomize):
                 <br />
                 <textarea id="inputForest" name="inputForest" cols="16" rows="8"></textarea>
                 <br />
                 <button>generate</button>
             </div>
             <div id="sim" class="hidden">
                    <h2>the current Simpson's Index is: 
                    </h2>
                    <div id="simpsons">
                    </div>
             </div>
             <div id="pushtray" class="overlay">
             </div>
         </div><!--close id="content"-->
     </body>
     </html>
 

#simpsons#sim 的 child。问题出在这段代码中:

  const curr = document.getElementById("sim").querySelectorAll("div");
  for (let i = 0; i < curr.length; i++) {
    if (!curr[i].hasAttribute("pinned")) {
      document.getElementById("sim").removeChild(curr[i]);
    }
  }

它有效地删除了 all div children of #sim 没有 pinned 属性。尝试仅删除第一个索引后的 divs,从而保留 #simpsons(这是 #sim 中的第一个 div):

for (let i = 1; i < curr.length; i++) {

function forestGenerate(content) {
  const forest = [];
  if (content.length === 0) {
    const possible = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""];
    for (let i = 0; i < 8; i++) {
      let text = '';
      for (let i = 0; i < 8; i++) {
        text += possible[Math.floor(Math.random() * possible.length)];
      }
      forest.push(text);
    }
  } else {
    const possible = [...content, ""];
    for (let i = 0; i < 8; i++) {
      let text = '';
      for (let i = 0; i < 8; i++) {
        text += possible[Math.floor(Math.random() * possible.length)];
      }
      forest.push(text);
    }
  }

  for (let i = 0; i < forest.length; i++) {
    let row = document.createElement("div");
    let newContent = document.createTextNode(forest[i]);
    row.appendChild(newContent);
    row.addEventListener("click", function() {
      row.style.backgroundColor = "grey";
      row.setAttribute("pinned", "yes");
    });

    document.getElementById("sim").appendChild(row);
  }
  return forest;
}

function simpsonsShow(forest) {
  const simpsonsIndex = forest =>
    1 - Object.entries(
      [...forest.join("")].reduce(
        (counts, emoji) => ({ ...counts,
          [emoji]: (counts[emoji] || 0) + 1
        }), {}
      )
    ).reduce(([top, bottom], [species, count]) => [top + (count * (count - 1)), bottom + count], [0, 0])
    .reduce((sumLilN, bigN) => sumLilN / (bigN * (bigN - 1)))

  var ind = simpsonsIndex(forest).toFixed(2);
  document.getElementById("simpsons").innerHTML = "";
  document.getElementById("simpsons").innerHTML = document.getElementById("simpsons").innerHTML + ind;
}

document.addEventListener("DOMContentLoaded", function() {

  let element = document.getElementById("sim");
  element.classList.add("hidden");

  let element1 = document.getElementById("pushtray");
  element1.classList.add("hidden");

  document.querySelector("div#intro button").addEventListener("click", function clicked() {

    document.getElementById("intro").style.display = "none";
    document.getElementById("sim").style.display = "block";
    document.getElementById("simpsons").style.display = "block";

    let content = document.getElementById("inputForest").value;
    let forest = forestGenerate(content);

    const ind = simpsonsShow(forest);

    if (ind <= .7) {
      let over = document.createElement("div");
      let newContent = document.createTextNode("WARNING: Simpson's Index Dropped To" + simpsonsIndex);
      over.appendChild(newContent);
      document.getElementById("pushtray").appendChild(over);
      document.getElementById("pushtray").style.zIndex = "100";
      document.getElementById("pushtray").style.right = "50px";
      document.getElementById("pushtray").style.position = "fixed";
      document.getElementById("pushtray").style.display = "block";
    }

    let button = document.createElement("button");
    button.appendChild(document.createTextNode("generate"));
    button.addEventListener("click", function() {
      const curr = document.getElementById("sim").querySelectorAll("div");
      for (let i = 1; i < curr.length; i++) {
        if (!curr[i].hasAttribute("pinned")) {
          document.getElementById("sim").removeChild(curr[i]);
        }
      }

      document.getElementById("sim").removeChild(button);

      forest = forestGenerate(content);

      simpsonsShow(forest);

      document.getElementById("sim").appendChild(button);
    });
    document.getElementById("sim").appendChild(button);
  });
});
.hidden {
  display: none;
}
<div id="content">
  <h1>FOREST SIMULATOR</h1>
  <div id="intro">
    starting forest (leave empty to randomize):
    <br />
    <textarea id="inputForest" name="inputForest" cols="16" rows="8"></textarea>
    <br />
    <button>generate</button>
  </div>
  <div id="sim" class="hidden">
    <h2>the current Simpson's Index is:
    </h2>
    <div id="simpsons">
    </div>
  </div>
  <div id="pushtray" class="overlay">
  </div>
</div>