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

标签 javascript html dom client-side

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

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 的子项。问题出在这段代码中:

  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]);
    }
  }

它有效地删除了 #simall div 子级,它们没有 pinned 属性。尝试仅删除第一个索引后的 div,从而保留 #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>

关于javascript - 当我第二次访问它时,HTML Div 元素变为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53491249/

相关文章:

javascript - 为什么无法将键码值记录到控制台窗口?

javascript - WordPress:如何将 get_the_title() 外部循环转换为 Javascript?

html - 为什么 float div会使下一个div占据整个空间?

javascript - 空格被列为子节点,但文本不是

java - 如何禁用/避免 Java-XML 中的 Ampersand-Escaping?

php - 使用 DOM 元素解析

javascript - 需要幻灯片 div 在更改幻灯片时将元素向下推

javascript - 捕捉/监听函数的执行

html - 你会认为 HTML + CSS + Webserver 是 MVC 吗?

html - 矩形定位被覆盖