javascript - 删除文本(使用 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 中。
解决方案
您正在附加一个文本节点,但#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>
推荐阅读
- python-3.x - Python Selenium 无法在 Azure 管道中运行
- jquery - jQuery kendo grid 如何为图标编辑、更新、取消、删除添加工具提示
- vue.js - 无法使用 Vue-Router 获取 URL 中的参数
- android - 如何从 Playstore 获取自适应高分辨率图标源?
- visual-studio - Visual Studio 2019 未发布 CSHTML 文件
- python - django Queryset filter(a__b__c=d): 获取 b 用于进一步过滤
- spring-boot - java.lang.IllegalStateException:之前查找 Docker 环境的尝试失败。不会重试。请查看日志并检查配置
- javascript - 在 JavaScript 中提交表单时动态导入模块
- python - python:日期必须是该月的第一周和第三周
- electron - 如何在 Electron 中安全地包含 C++ SDK