首页 > 解决方案 > 删除文本(使用 JavaScript 删除)后,无法在元素中重新附加文本(使用 JavaScript 追加)

问题描述

如何使用 JavaScript append() 和 remove() 追加和删除元素?目前,我的代码能够在用户单击“附加文本”时为 div 元素附加文本,并在用户单击“删除文本”时从元素中删除文本。

但这只会发生一轮 - 这意味着在用户单击“删除文本”时删除文本后,当用户再次单击“附加文本”时无法重新附加文本。我不知道为什么 JavaScript append() 在使用 remove 从 div 元素中删除文本后不起作用。

这是我的代码:

<!DOCTYPE html>
<html>
<body>

<h1> Using JavaScript append() & remove () </h1>

<div id="demo"> </div>  <!-- text is appended & removed here -->

<button onclick="appendText()"> Append Text </button>

<button onclick="removeText()"> Remove Text </button>

<script>

var myobj = document.getElementById("demo");

function appendText() 
{

     //var myobj = document.getElementById("demo");
     myobj.append("Just a text");

}

function removeText() 
{
     //var myobj = document.getElementById("demo");
     myobj.remove();
}

</script>

</body>
</html>

你们会用纯 JavaScript(不是 JQuery)方法解释我哪里出错了,因为我只知道 JavaScript。根据我对我所做的问题的研究,几乎所有的解决方案都在 JQuery 中。

标签: javascripthtml

解决方案


您正在附加一个文本节点,但#demo您选择的是父元素。首先向下选择文本节点,然后将其删除。

const demo = document.getElementById("demo");

function appendText() {
  demo.append("Just a text");
}

function removeText() {
  demo.childNodes[demo.childNodes.length - 1].remove();
}
<h1> Using JavaScript append() & remove () </h1>

<div id="demo"></div>
<!-- text is appended & removed here -->

<button onclick="appendText()"> Append Text </button>

<button onclick="removeText()"> Remove Text </button>

或清除 textContent

const demo = document.getElementById("demo");

function appendText() {
  demo.append("Just a text");
}

function removeText() {
  demo.textContent = '';
}
<h1> Using JavaScript append() & remove () </h1>

<div id="demo"></div>
<!-- text is appended & removed here -->

<button onclick="appendText()"> Append Text </button>

<button onclick="removeText()"> Remove Text </button>


推荐阅读