首页 > 解决方案 > 通过 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);
}

请帮忙!

标签: javascripthtmlcss

解决方案


由于您没有提供任何代码,所以我根据您的问题描述编写了解决方案。看起来您正在努力创建一个待办事项列表。我使用了 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>


推荐阅读