输出.appendchild on< li> &< span>地图功能中的元素

发布于 2025-02-10 13:16:36 字数 1488 浏览 1 评论 0原文

我将待办事项存储在一系列对象上。我想映射数组以获取HTML元素。我可以使用innerhtml来做到这一点,但是我想用createElement来做。

我期望< li><似乎附加不起作用。

html代码:

<div class="todo">
      <h1>Todo</h1>
      <form name="todo--form">
        <input type="text" name="todo--input" />
        <button
          type="submit"
          name="todo--submit"
          class="p-2 bg-slate-500 rounded"
        >
          Add
        </button>
      </form>
      <ul class="todo--list"></ul>
    </div>

JS代码:

const addTodoForm = document.querySelector(`[name="todo--form"]`);
const todoList = document.querySelector('.todo--list');
const todos = [];

// function getLabel() {}

function handleSubmit(e) {
  e.preventDefault();
  const text = this.querySelector(`[name="todo--input"]`).value;
  const item = {
    text: text,
    finished: false,
  };

  if (text) {
    todos.push(item);
    addTodoForm.reset();
    const todoItems = todos.map((todo, i) => {
      let newSpan = document.createElement('span');
      let newLi = document.createElement('li');
      newSpan.textContent = todo.text;
      let newEl = newLi.append(newSpan);
      return newEl;
    });
    console.log(todoItems);
    todoList.append(...todoItems);
  }
  return;
}

addTodoForm.addEventListener('submit', handleSubmit);

我只得到&lt; span&gt; span&gt;作为输出。

I am storing the todo-items on an array of objects. I want to map the array to get the HTML elements. I am able to do this using innerHTML but I want to do it with createElement.

I am expecting <li><span>TEXT</span></li> output but I am getting only span. It seems append is not working.

HTML code :

<div class="todo">
      <h1>Todo</h1>
      <form name="todo--form">
        <input type="text" name="todo--input" />
        <button
          type="submit"
          name="todo--submit"
          class="p-2 bg-slate-500 rounded"
        >
          Add
        </button>
      </form>
      <ul class="todo--list"></ul>
    </div>

JS Code :

const addTodoForm = document.querySelector(`[name="todo--form"]`);
const todoList = document.querySelector('.todo--list');
const todos = [];

// function getLabel() {}

function handleSubmit(e) {
  e.preventDefault();
  const text = this.querySelector(`[name="todo--input"]`).value;
  const item = {
    text: text,
    finished: false,
  };

  if (text) {
    todos.push(item);
    addTodoForm.reset();
    const todoItems = todos.map((todo, i) => {
      let newSpan = document.createElement('span');
      let newLi = document.createElement('li');
      newSpan.textContent = todo.text;
      let newEl = newLi.append(newSpan);
      return newEl;
    });
    console.log(todoItems);
    todoList.append(...todoItems);
  }
  return;
}

addTodoForm.addEventListener('submit', handleSubmit);

I am getting only <span><span> as output.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

醉生梦死 2025-02-17 13:16:36

当提交&lt; form&gt;时,一次只列出一个项目,因此无需构建一个项目数组。 BTW事件处理程序(绑定到事件的函数)不会像普通函数一样返回值,但是有一些间接的方法可以从它们中获取值(例如从OP代码中,该数组在函数推动对象之外)。

详细信息在示例中评论

// Reference <form>
const form = document.forms.todo;
// Reference <ul>
const list = document.querySelector('.list');
// Define array for storage
let tasks = [];

// Bind "submit" event to <form>
form.onsubmit = handleSubmit;

// Event handlers passes Event Object by default
function handleSubmit(e) {
  // Stop default behavior during a "submit"
  e.preventDefault();
  // Reference all form controls
  const IO = this.elements;

  /*
  Define {item}
  Add current timestamp to object {item}
  Add <input> text to {item}
  Add {item} to [tasks]
  Clear <input>
  */
  let item = {};
  item.log = Date.now();
  item.task = IO.data.value;
  tasks.push(item);
  IO.data.value = '';

  /*
  Create <time>
  Assign timestamp <time>
  Convert timestamp into a readable date and time
  Add formatted datetime as text to <time>
  */
  const log = document.createElement('time');
  log.datetime = item.log;
  let date = new Date(item.log);
  log.textContent = date.toLocaleString();

  /*
  Create <output>
  Add text of <input> to <output>
  */
  const txt = document.createElement('output');
  txt.value = item.task;

  /*
  Create <button>
  Add type, class, and the text: "Delete" to <button>
  */
  const btn = document.createElement('button');
  btn.type = 'button';
  btn.className = 'delete';
  btn.textContent = 'Delete';

  // Create <li>
  const li = document.createElement('li');

  // Append like crazy
  li.append(log);
  li.append(txt);
  li.append(btn);
  list.append(li);
  console.log(tasks);
}
html {
  font: 300 2ch/1.2 'Segoe UI';
}

input,
button {
  font: inherit;
}

output {
  display: inline-block;
  margin: 0 8px 8px;
}

button {
  cursor: pointer;
}

.as-console-row::after {
  width: 0;
  font-size: 0;
}

.as-console-row-code {
  width: 100%;
  word-break: break-word;
}

.as-console-wrapper {
  max-height: 30% !important;
  max-width: 100%;
}
<form id='todo'>
  <fieldset>
    <legend>ToDo List</legend>
    <input id='data' type="text" required>
    <button class="p-2 bg-slate-500 rounded">Add</button>
    <ul class="list"></ul>
  </fieldset>
</form>

When the <form> is submitted there's only one item being appended to list at a time so there's no need to build a one item array. BTW event handlers (functions that are bound to an event) don't return values like a normal function can, but there are indirect ways to get values from them (like from your OP code, that array outside of the function pushing objects).

Details are commented in example

// Reference <form>
const form = document.forms.todo;
// Reference <ul>
const list = document.querySelector('.list');
// Define array for storage
let tasks = [];

// Bind "submit" event to <form>
form.onsubmit = handleSubmit;

// Event handlers passes Event Object by default
function handleSubmit(e) {
  // Stop default behavior during a "submit"
  e.preventDefault();
  // Reference all form controls
  const IO = this.elements;

  /*
  Define {item}
  Add current timestamp to object {item}
  Add <input> text to {item}
  Add {item} to [tasks]
  Clear <input>
  */
  let item = {};
  item.log = Date.now();
  item.task = IO.data.value;
  tasks.push(item);
  IO.data.value = '';

  /*
  Create <time>
  Assign timestamp <time>
  Convert timestamp into a readable date and time
  Add formatted datetime as text to <time>
  */
  const log = document.createElement('time');
  log.datetime = item.log;
  let date = new Date(item.log);
  log.textContent = date.toLocaleString();

  /*
  Create <output>
  Add text of <input> to <output>
  */
  const txt = document.createElement('output');
  txt.value = item.task;

  /*
  Create <button>
  Add type, class, and the text: "Delete" to <button>
  */
  const btn = document.createElement('button');
  btn.type = 'button';
  btn.className = 'delete';
  btn.textContent = 'Delete';

  // Create <li>
  const li = document.createElement('li');

  // Append like crazy
  li.append(log);
  li.append(txt);
  li.append(btn);
  list.append(li);
  console.log(tasks);
}
html {
  font: 300 2ch/1.2 'Segoe UI';
}

input,
button {
  font: inherit;
}

output {
  display: inline-block;
  margin: 0 8px 8px;
}

button {
  cursor: pointer;
}

.as-console-row::after {
  width: 0;
  font-size: 0;
}

.as-console-row-code {
  width: 100%;
  word-break: break-word;
}

.as-console-wrapper {
  max-height: 30% !important;
  max-width: 100%;
}
<form id='todo'>
  <fieldset>
    <legend>ToDo List</legend>
    <input id='data' type="text" required>
    <button class="p-2 bg-slate-500 rounded">Add</button>
    <ul class="list"></ul>
  </fieldset>
</form>

小帐篷 2025-02-17 13:16:36
    const todoItems = todos.map((todo, i) => {
     let newSpan = document.createElement('span');
     let newLi = document.createElement('li');
     newSpan.textContent = todo.text;
     let newEl = newLi.append(newSpan);
     return newLi;
    });
    const todoItems = todos.map((todo, i) => {
     let newSpan = document.createElement('span');
     let newLi = document.createElement('li');
     newSpan.textContent = todo.text;
     let newEl = newLi.append(newSpan);
     return newLi;
    });
平定天下 2025-02-17 13:16:36

在这个代码块中,我相信创建的Newel变量不正确。尝试将newli.append(Newspan)更改为newli.appendchild(Newspan

  if (text) {
    todos.push(item);
    addTodoForm.reset();
    const todoItems = todos.map((todo, i) => {
      let newSpan = document.createElement('span');
      let newLi = document.createElement('li');
      newSpan.textContent = todo.text;
      let newEl = newLi.appendChild(newSpan);
      return newEl;
    });
    console.log(todoItems);
    todoList.append(...todoItems);
  }
  return;

In this block of code, I believe the newEl variable being created isn't correct. Try changing newLi.append(newSpan) to newLi.appendChild(newSpan)

This is also listed below

  if (text) {
    todos.push(item);
    addTodoForm.reset();
    const todoItems = todos.map((todo, i) => {
      let newSpan = document.createElement('span');
      let newLi = document.createElement('li');
      newSpan.textContent = todo.text;
      let newEl = newLi.appendChild(newSpan);
      return newEl;
    });
    console.log(todoItems);
    todoList.append(...todoItems);
  }
  return;
池木 2025-02-17 13:16:36

感谢您的所有答案。
在阅读附录和附录的文档文档后,使用这些方法似乎无法将元素保存到变量中。

我只需要返回附录li元素。

   const todoItems = todos.map((todo, i) => {
      let newSpan = document.createElement('span');
      let newLi = document.createElement('li');
      newLi.setAttribute('data-index', i);
      const todoTextNode = document.createTextNode(todo.text);
      newSpan.appendChild(todoTextNode);
      newLi.appendChild(newSpan);
      return newLi;
    });

Thanks for all the answers.
Upon reading on the documentation of append and appendChild, it seems elements cannot be saved into a variable upon using these methods.

I just need to return the append li element.

   const todoItems = todos.map((todo, i) => {
      let newSpan = document.createElement('span');
      let newLi = document.createElement('li');
      newLi.setAttribute('data-index', i);
      const todoTextNode = document.createTextNode(todo.text);
      newSpan.appendChild(todoTextNode);
      newLi.appendChild(newSpan);
      return newLi;
    });

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文