首页 > 解决方案 > 元素编辑按钮应该只编辑“那个”元素,而不是更新所有

问题描述

所以我正在尝试为收藏夹栏制作​​编辑功能。编辑一个框是可以的,但是当我尝试编辑另一个框时,我之前单击的所有框也会被编辑。这是一个带有完整代码的 jsfiddle:https ://jsfiddle.net/1exrf9h8/1/

我试图理解为什么我的 editFavorite 函数会更新多个框而不仅仅是一个框。

function clickEdit(input, title, url, plus, editIcon, anchorEdit, editBtn)
{
  let i = editIcon.length - 1;

  editIcon[i].addEventListener("click", function(event){
    input.style.display = "block";
    title.value = plus[i + 1].textContent;
    url.value = anchorEdit[i].href;
    console.log(i);
    console.log(anchorEdit[i]);
    editFavorite(anchorEdit[i], url, title, input, editBtn);
  });
}

function editFavorite(changed, url, title, input, editBtn)
{
  editBtn.addEventListener("click", function(){
    changed.href = url.value;
    changed.textContent = title.value;
    input.style.display = "none";
  });
}

标签: javascripthtmlcss

解决方案


您的逻辑、架构和事件处理程序的使用存在一些问题,让我们以更OOP的方式试一试,这样您就可以真正让它工作并了解正在发生的事情。

每个收藏夹本身就是一个对象,它可以产生更新自己。

function favorite(newTitle, newUrl) {
  this.element = container.appendChild(document.createElement("div"));
  this.title = this.element.appendChild(document.createElement("h2"));
  this.url = this.element.appendChild(document.createElement("h2"));

    this.update = (newTitle, newUrl) => {
      this.title.textContent = newTitle;
      this.url.textContent = newUrl;
    }

    this.createButton = () => {
      button = this.element.appendChild(document.createElement("button"));
      button.append("Edit");
      button.addEventListener("click", () => {
        let titleInput = document.getElementById("title").value;
        let urlInput = document.getElementById("url").value;

        this.update(titleInput, urlInput);
      })
  }

  this.update(newTitle, newUrl);
  this.createButton();
}

然后让我们有一个简单的表单,我们可以在其中接受输入,使用它进行编辑,并创建一个新的收藏夹。

<input id="title" type="text" name="title" placeholder="Title">
<input id="url" type="text" name="url" placeholder="Url">
<button id="submit">Create New</button>

现在是实际的提交逻辑。

  document.getElementById("submit").addEventListener("click", () => {
    let titleInput = document.getElementById("title").value;
    let urlInput = document.getElementById("url").value;

    if (!titleInput.length || !urlInput.length) return;
    let newFavorite = new favorite(titleInput, urlInput);
    container.appendChild(newFavorite.element);
 });

https://jsfiddle.net/p50L27us/48/


推荐阅读