javascript 如何通过单击HTML按钮向div添加多个元素

mnemlml8  于 2023-03-21  发布在  Java
关注(0)|答案(1)|浏览(215)

我一直在做一个ToDo应用程序,我已经设法通过单击按钮创建一个任务,事情是,我希望它继续创建任务,因为createButton被单击,但它只做一次。

//inputs
let ids1 = document.getElementById('ids')
let ids2 = document.getElementById('ids2')
let ids3 = document.getElementById('ids3')
let ids4 = document.getElementById('ids4')

//create paragraph
let paro = document.createElement('p')

let createButton = document.getElementsByClassName('create')
let newd = document.getElementsByClassName('newd')

function createTask (){ 

paro.innerText = ids1.value + ' ' + ids2.value + ' ' + ids3.value + ' ' + ids4.value

if(ids1.value !== ''){ 
    if(ids2.value !== ''){ 
        if(ids3.value !== ''){ 
            newd[0].appendChild(paro)
        }else {
            alert('date is required')
        }

    }else {
        alert('description description is required')
    }
}else {
     alert('title is required')
}
}

 createButton[0].addEventListener('click', createTask)
pw136qt2

pw136qt21#

createTask事件处理程序中创建<p>元素,以便每次都创建一个新元素,而不是追加相同的元素。
演示:

let ids1 = document.getElementById('ids')
let ids2 = document.getElementById('ids2')
let createButton = document.querySelector('.create');
let newd = document.querySelector('.newd');

function createTask() {
  let paro = document.createElement('p');
  paro.innerText = ids1.value + ' ' + ids2.value;
  newd.appendChild(paro);
}
createButton.addEventListener('click', createTask);
<input id="ids"> <input id="ids2">
<button class="create">Create</button>
<div class="newd"></div>

相关问题