javascript - 通过 javascopt 制作一个 html 元素
问题描述
我想写一个函数来创建一个html标签我有一个输入标签,这个函数必须将此输入的值添加到创建的html元素中,并在创建的元素右侧添加一个“x”以通过单击删除元素但是我无法添加“x”按钮!
这是我的脚本:
function myFunction() {
x = document.getElementById("myText").value;
var node = document.createElement("p");
var node1 = document.createElement("button");
var textnode = document.createTextNode(x);
node.appendChild(textnode);
document.getElementById("print").appendChild(node);
}
请帮忙!
解决方案
由于您没有提供任何代码,所以我根据您的问题描述编写了解决方案。看起来您正在努力创建一个待办事项列表。我使用了 flexbox 布局来正确对齐元素。
来看看吧:
const textfield = document.querySelector('#textfield');
const addBtn = document.querySelector('#addBtn');
const list = document.querySelector('#list');
// add click listener
addBtn.addEventListener('click', addItemToList);
function addItemToList() {
const value = textfield.value;
if (value !== '') {
const listNode = document.createElement('li');
// add value in the span tag
const spanNode = document.createElement('span');
spanNode.innerText = value;
// create a delete button with value 'x' and add click listener
const deleteButton = document.createElement('button');
deleteButton.innerText = 'x';
deleteButton.addEventListener('click', deleteListNode)
// add span and button inside the list node
listNode.append(spanNode, deleteButton);
// append list in the ul
list.append(listNode);
}
}
function deleteListNode(event) {
target = event.target;
// remove parent node i.e. <li> from dom
target.parentElement.remove();
}
* {
box-sizing: border-box;
}
body {
/* centerd alignment vertically and horizontally */
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.wrapper {
max-width: 20em;
}
#textfield, #list > li, #addBtn {
padding: 7px 10px;
min-width: 70px;
}
ul {
width: 100%;
margin-top: 20px;
}
li {
/* to create space between text and cross button */
display: flex;
width: 100%;
justify-content: space-between
}
<div class="wrapper">
<div>
<input id="textfield" type="text"/>
<button id="addBtn">Add</button>
</div>
<ul id="list">
</ul>
</div>
推荐阅读
- css - SVG 动画 Stroke-Dasharray
- nuxt.js - 从文本编辑器编写林业模板文件
- php - 如何使用 Laravel-Excel 导出以生成 SUBTOTAL 输出?
- vue.js - Vue:如果数据库写入失败,则撤消从 v-for 数组中删除项目
- macos - 如何在 Mac 上更新 cocoapods 以实现颤振而不会出现错误?
- c - 试图将 char 类型转换为 float 类型,但 gettng 分段错误
- c# - 如何在asp.net core中设置路由参数
- android - 来自 URL 的 MapBox Lcoation 组件图像
- javascript - 浏览器扩展开发问题:访问网站功能?
- javascript - 如何从 CSS 背景图像中获取图像源