首页 > 解决方案 > 输入文本未显示在 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);
});

标签: javascripthtml

解决方案


您的代码实际上正在运行。但它在复选框输入中生成标签。这就是为什么你无法看到它。

问题出在以下部分

document
    .querySelector("#todoItem")
    .appendChild(div)
    .appendChild(checkBox)
    .appendChild(checkBoxLabel)

这是做什么的?

这将首先从具有 id 的 DOM 中选择一个元素todoItem在里面你的 div 将被附加。在该 div 中,checkBox作为输入的,将被附加。在该输入内部,checkBoxLabel将附加标签。

所以你的层次结构就像,在容器内的 div ,在那个 div 的里面,#todoItem在里面。checkBoxcheckBoxLabelcheckBox

checkBoxLabel您在复选框内附加。它应该在复选框的同一级别,或者输入可以放在标签内。复选框内的标签将不可见。您可以将OR放在checkbox内部,也可以将它们放在相同的层次结构中。labelcheckboxlabeldiv

在标签内放置复选框

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>


推荐阅读