javascript - 输入文本未显示在 Html 页面上
问题描述
我并试图将一个基本网页制作为一个项目,并且无法让我的文本显示为使用 javaScript 注入的标签标记。如果有人有任何想法或可以指出我正确的方向,那就太好了。这是我遇到问题的代码片段。
let todo = [
{
text: "Item 1",
completed: true,
},
{
text: "Item 2",
completed: false,
},
{
text: "Item 3",
completed: false,
},
{
text: "Item 4",
completed: false,
},
{
text: "Item 5",
completed: true,
},
];
todo.forEach(function (todos, index) {
const p = document.createElement("p");
const div = document.createElement("div");
const checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.id = `newTodo${index}`;
checkBox.value = `todoItem${index}`;
const checkBoxLabel = document.createElement("label");
checkBoxLabel.htmlFor = `todoItem${index}`;
checkBoxLabel.innerText = todos.text; //"This is the text that is not being rendered to the browser"
document
.querySelector("#todoItem")
.appendChild(div)
.appendChild(checkBox)
.appendChild(checkBoxLabel);
});
解决方案
您的代码实际上正在运行。但它在复选框输入中生成标签。这就是为什么你无法看到它。
问题出在以下部分
document
.querySelector("#todoItem")
.appendChild(div)
.appendChild(checkBox)
.appendChild(checkBoxLabel)
这是做什么的?
这将首先从具有 id 的 DOM 中选择一个元素todoItem
。在里面你的 div 将被附加。在该 div 中,checkBox
作为输入的,将被附加。在该输入内部,checkBoxLabel
将附加标签。
所以你的层次结构就像,在容器内的 div ,在那个 div 的里面,#todoItem
在里面。checkBox
checkBoxLabel
checkBox
checkBoxLabel
您在复选框内附加。它应该在复选框的同一级别,或者输入可以放在标签内。复选框内的标签将不可见。您可以将OR放在checkbox
内部,也可以将它们放在相同的层次结构中。label
checkbox
label
div
在标签内放置复选框
document
.querySelector("#todoItem")
.appendChild(div)
.appendChild(checkBoxLabel)
.appendChild(checkBox);
这将使复选框被放置在标签之后。像下面的那个
将复选框和标签放置在具有相同层次结构的 div 内。
div
.appendChild(checkBox);
div
.appendChild(checkBoxLabel);
document
.querySelector("#todoItem")
.appendChild(div);
这将首先显示复选框,然后显示如下标签
请找到第二个示例的工作小提琴。
const todo = [
{ text: "Item 1", completed: true, },
{ text: "Item 2", completed: false, },
{ text: "Item 3", completed: false, },
{ text: "Item 4", completed: false, },
{ text: "Item 5", completed: true, },
];
todo.forEach(function (todos, index) {
const p = document.createElement("p");
const div = document.createElement("div");
const checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.id = `newTodo${index}`;
checkBox.value = `todoItem${index}`;
// added checking condition
checkBox.checked = todos.completed;
const checkBoxLabel = document.createElement("label");
checkBoxLabel.htmlFor = `todoItem${index}`;
checkBoxLabel.innerText = todos.text;
// Place checkbox first then the label, Both on the div
div
.appendChild(checkBox);
div
.appendChild(checkBoxLabel);
document
.querySelector("#todoItem")
.appendChild(div);
});
<div id="todoItem"></div>
推荐阅读
- c - 如何将 C-printf 字符串格式化为等于 bash-printf 字符串
- go - 赛尔戈。如何使用自定义对象和时间戳比较
- javascript - 类列表切换多个元素
- r - 如何停止在不同计算机上选择相同的“随机”行?
- r - 在列内删除和求和
- javascript - 如何在 es6 中的 javascript 中循环遍历嵌套对象的值
- git - 在 Azure DevOps 中克隆私有 BitBucket 存储库
- javascript - 使用 Jquery 将多个函数分配给同一个类/元素?
- android - 如何在Android上有一个连续运行的后台任务?
- angular - 如何为 Angular 应用程序正确创建 Docker 映像?