javascript - Vanilla JS/HTML:将 html 对象连接到内部数据模型/数组的最佳实践
问题描述
我有一个缩略图视图,其中包含内部存储在数组中的 x 项。在初始请求之后,不再有服务器通信,因此之后一切都在浏览器中处理。
在我当前的解决方案中,我在我的内部数据模型中为每个 html 缩略图项提供了它们相应索引的 id,以便在单击缩略图后我知道要加载哪些数据。
在我尝试实现删除操作之前,我认为这是一个好主意,因此可以删除任何位置的任何项目,也可以拖放缩略图项目。
因此,在我当前的解决方案中,我需要在每次更新后运行每个单独的 html 缩略图项目以调整索引,这不是一个很好的解决方案。
我不相信我会遇到性能问题,因为缩略图将包含超过 100 个项目是非常值得怀疑的,但我想知道是否有更好的解决方案或最佳实践来使它更好。
我不能以任何方式或形式影响数据模型/数组,因此不能选择带有 uids 的地图,也不能使用任何框架,因此需要一个普通的解决方案。
<button class="thumbNailItem" id="tni#5"><h3>BOLD</h3><p>My Description</p></button>
this.deleteStep = function() {
let thumbParent = document.getElementById('thumbNailParent');
this.curTC.testSteps.splice(this.curStep.index, 1);
thumbParent.removeChild(thumbNailParent.children[this.curStep.index]);
//would need to implement loop to correct all 'tni#ids'
if (this.curStep.index <= thumbParent.children.length) {
thumbParent.children[this.curStep.index].click();
}
解决方案
解释
考虑到我们对您正在寻找的究竟是什么知之甚少,这里有一个足够简单的方法,您可以使用本机 JavaScript 来简单地处理数据、一些事件和一些渲染。
如果你需要一些文档来理解这段代码,我强烈建议你看看MDN,我的意思是我想你可以在很大程度上理解它。如前面在评论中所述,为了实现这一点,我只是使用模板文字来处理 HTML 的呈现方式。
您可以使用许多方法从根本上解决相同的问题,但在我看来,这种方法对于正在发生的事情来说是干净、清晰和简洁的。
(function () {
"use strict";
// Just some dummy data for the time being.
let data = [
{name: "Jack", age: 18},
{name: "Leah", age: 32},
{name: "Jay", age: 45}
];
// Simple reference to the app div.
const app = document.getElementById("app");
// How you want to handle the click event for each button.
const handler = e => {
data.splice(e.target.id, 1);
render();
};
// A simple function to handle dispatching the events.
const dispatchEvents = () => {
document.querySelectorAll(".profile button").forEach(btn => btn.onclick = handler);
};
// A simple render method.
const render = () => {
app.innerHTML = data.map((o, i) => `<div class="profile">
<p class="username">Name: ${o.name}</p>
<p class="userage">Age: ${o.age}</p>
<button id=${i}>DELETE</button>
</div>`).join("");
dispatchEvents();
};
// Initial render.
render();
})();
<div id="app"></div>
推荐阅读
- c++ - 请让我知道如何在 APDU 中使用参考控制位表
- mysql - 如何在我的 SQL 查询中显示额外的列
- python - sklearn随机森林分类器的奇怪行为
- java - Java 对象的动态 Json 文件
- android - 我的应用程序中的 en-rZA 字符串文件正在为 en-UK 语言环境设置字符串
- postgresql - .Net 核心中的 postgresql 行级安全性
- html - 背景图像的 SCSS SASS 路径问题
- reactjs - 我可以在 React 中使字符串可点击吗?
- selenium - Katalon 无法单击存在的对象
- javascript - Flex Box:自动换行