用javascript创建一个新元素 [英] Creating a new element with javascript

查看:41
本文介绍了用javascript创建一个新元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用文本输入创建一个新的 li 元素.问题是出现文本时,并没有创建我可以设置样式的实际 li 元素.文本在那里,但只是连续排成一行.这是我的html:

I'm trying to create a new li element using a text input. The problem is while the text is appearing, it doesn't to create an actual li element that I can style. The text is there, but it just forms right next to each other in a row. Here is my html:

const button = document.getElementById('submit');

button.addEventListener ("click", () => {
  var taskInput = document.getElementById('task').value;
  // Creating the text for list item.
  if (taskInput === '') { // Prevents empty list item.
    alert("You have to type a task!");
  } else {
  var listItem = document.createElement("li"); // Create li element.
  var text = document.createTextNode(taskInput); // Create text for list item.
  listItem.appendChild(text); // Append text to li element.
  }
  
  //Add new list item to list
  var list = document.getElementById("list");
  list.appendChild(text);
  
});

 

<body>
<h1>Start your list!</h1>
<div class="input">
<input type="text" id="task">
<button id="submit">Create</button>
</div>
<section id="list">
</section>
</body>

推荐答案

只需使用< ul> 而不是< section> 并将其附加到listeItem 而不是 text .

just use <ul> instead of <section> and append to it listeItem and not text.

const button = document.getElementById('submit');

button.addEventListener ("click", () => {
  var taskInput = document.getElementById('task').value;
  // Creating the text for list item.
  if (taskInput === '') { // Prevents empty list item.
alert("You have to type a task!");
  } else {
  var listItem = document.createElement("li"); // Create li element.
  var text = document.createTextNode(taskInput); // Create text for list item.
  listItem.appendChild(text); // Append text to li element.
  }

  //Add new list item to list
  var list = document.getElementById("list");
  list.appendChild(listItem);

});

<body>
<h1>Start your list!</h1>
<div class="input">
<input type="text" id="task">
<button id="submit">Create</button>
</div>
<ul id="list">
</ul>
</body>

这篇关于用javascript创建一个新元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆