元素编辑按钮应该只编辑"that"元素,而是更新所有



所以我正在尝试为收藏夹栏制作一个编辑功能。编辑一个框是可以的,但是当我尝试编辑另一个框时,我之前单击的所有框也会被编辑。这是一个包含完整代码的 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";
});
}

在逻辑、体系结构和事件处理程序的使用中存在一些问题,让我们以更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/

该问题是由编辑收藏夹函数引起的。 当您调用 editFavorite 函数时,会自动启动新的侦听器。艾薇点击开始新的。

解决方案是" ,{一次 : true} ">

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

最新更新