javascript - 元素编辑按钮应该只编辑“那个”元素,而不是更新所有
问题描述
所以我正在尝试为收藏夹栏制作编辑功能。编辑一个框是可以的,但是当我尝试编辑另一个框时,我之前单击的所有框也会被编辑。这是一个带有完整代码的 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);
});
推荐阅读
- python - 如何从元素中提取链接?
- cordova - 如何使用 cordova.inAppBrower 禁用全屏视图
- c++ - 模板化构造函数无法执行转换
- python - 并排绘制多个不同大小的列表?
- javascript - 如何重新排列 WordPress REST API 评论?
- node.js - Redux-Form 字段仅出现在输入底部的一行而不是框。有没有办法拿到盒子?
- ios - 使 UIAccessibilityTrait 可调整忽略双击(如按钮)迅速
- arrays - 如何从 CoreData TableView 数组中提取 Data Array,将其放入新的 Array 并将其导出为 csv?
- android - 如何优雅地处理 sigaction() 并回馈父进程
- apiblueprint - 使用 V4 交互式文档在本地渲染养蜂场文档