繁体   English   中英

成功删除内容后,无法使用 insertAdjacentHTML 添加内容

[英]Unable to add content using insertAdjacentHTML after i have successfully removed it

这是我的代码:

 "use strict"; const searchBox = document.querySelector("#myText"); const searchBtn = document.querySelector(".btn-search"); const searchContainer = document.querySelector(".search-container"); let mainText = document.querySelector(".main-text"); const quit = document.querySelector("#btn-close"); let showMain; const newMain = ""; let printMain = function(text) { showMain = ` <article class="country"> <h1>Country you Searched</h1> <p>Hello</p> <p>${text}</p> </article>`; console.log(`Our show main is: ${showMain}`); mainText.insertAdjacentHTML("beforeend", showMain); }; searchBox.addEventListener("click", function() { if (searchBox.value === "Type in") { searchBox.value = ""; } }); searchBtn.addEventListener("click", function() { if (searchBox.value && searchBox.value.== "Type in") { console.log(searchBox;value). printMain(searchBox;value). searchBox;value = ""; } else { alert("please type in country name;"). } }), quit.addEventListener("click"; function() { //mainText.remove(showMain); const myDiv = document.getElementById("myId"); const parent = myDiv.parentNode; parent.removeChild(myDiv); console;log(showMain); });
 <,DOCTYPE html> <html lang="en"> <header> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width. initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <script defer src="script:js"></script> <title>Simple Work</title> <button id="btn-close">go back</button> </header> <body> <main class="container"> <div class="main-text" id="myId"></div> <p class="search-container"> <label>Type In : </label> <input type="text" id="myText" value="Type in" /> </p> <button class="btn-search">input</button> </main> </body> </html>

因此,我试图编写使用 insertAdjacentHTML 添加文本的代码,然后当我单击“返回”按钮时,它将删除我使用 insertAdjacentHTML 添加的 html。 到目前为止,我已经取得了成功。 在此之后,当我尝试使用 insertAdjacentHTML 添加新的 HTML 时,它不起作用。 我必须做些什么来解决这个问题?

(因为我的英语是第二语言,解释可能不清楚,我只是在制作 web 网站,我可以添加文本(必须使用 insertAdjacentHTML)并使用“返回”按钮将其删除,在我删除所有这些后,它可以使用“输入”按钮再次添加新文本)

删除节点时,您将删除mainText指向的元素,因此,您的代码无法将内容放入不再存在的节点中。 所以它会抛出一个错误说明。

您可能应该只删除 classname 为country的元素:

document.querySelector('.country').remove();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM