【问题标题】:create a Edit Button while manipulating DOM in javascript在 javascript 中操作 DOM 时创建一个编辑按钮
【发布时间】:2022-01-16 14:09:45
【问题描述】:

我正在创建一个简单的 TODO APP,它会在添加任务时添加、删除和编辑任务,我正在尝试弄清楚如何编辑任务。我应该创建一个新的 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(){      

    })
  })
})



【问题讨论】:

  • 如果您的整个问题只是“我应该创建一个<p>”,那么这只不过是一个基于意见的问题,而且这些都是题外话。如果您遇到更具体的问题,请详细说明它们是什么以及您遇到的问题。见How to Ask。当您不具体时,很难提供帮助

标签: javascript dom


【解决方案1】:

有很多方法可以做到这一点。一种方法是为您的段落使用属性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(); 
});

【讨论】:

    猜你喜欢
    • 2019-04-09
    • 2014-08-02
    • 2015-08-13
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多