我正在創建一個簡單的 TODO 應用程式,它在添加任務時添加、洗掉和編輯任務,我試圖弄清楚如何編輯任務。我應該創建一個新的 P 標簽并使其等于 par.value 嗎?
h1.innerText = 'TODO LIST';
document.body.appendChild(h1);
const input = document.createElement('input');
document.body.appendChild(input);
const addBtn = document.createElement('button');
addBtn.innerText = 'Add';
document.body.appendChild(addBtn);
const container = document.createElement('div');
container.innerText = 'Output';
document.body.appendChild(container);
addBtn.addEventListener('click', function(){
const par = document.createElement('p');
par.innerText = input.value;
container.appendChild(par);
const deleteBtn =document.createElement('button');
deleteBtn.innerText = 'Delete';
par.appendChild(deleteBtn);
const editBtn = document.createElement('button');
editBtn.innerText = 'Edit';
par.appendChild(editBtn);
deleteBtn.addEventListener('click', function(){
this.parentElement.remove();
editBtn.addEventListener('click', function(){
})
})
})
uj5u.com熱心網友回復:
有很多方法可以做到這一點。一種方法是contenteditable為您的段落使用該屬性。看這個例子:
const h1 = document.createElement('h1');
h1.innerText = 'TODO LIST';
document.body.appendChild(h1);
const input = document.createElement('input');
document.body.appendChild(input);
const addBtn = document.createElement('button');
addBtn.innerText = 'Add';
document.body.appendChild(addBtn);
const container = document.createElement('div');
container.innerText = 'Output';
document.body.appendChild(container);
addBtn.addEventListener('click', function() {
const par = document.createElement('p');
par.innerText = input.value;
container.appendChild(par);
const deleteBtn = document.createElement('button');
deleteBtn.innerText = 'Delete';
container.appendChild(deleteBtn);
const editBtn = document.createElement('button');
editBtn.classList.add('edit');
editBtn.innerText = 'Edit';
container.appendChild(editBtn);
deleteBtn.addEventListener('click', function() {
this.parentElement.remove();
editBtn.addEventListener('click', function() {
})
})
})
// Since the selector ".edit" is dynamic, listen to all elements
document.querySelector('*').addEventListener('click', (e) => {
// Return, if the element has not the class "edit"
if (e.target.className !== 'edit') return
// Set attribute to the paragraph
e.target.previousSibling.previousSibling.setAttribute('contenteditable', 'true');
// focus the paragraph
e.target.previousSibling.previousSibling.focus();
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/379596.html
標籤:javascript dom
下一篇:如何在物件陣列中搜索特定值
