我有一个缩略图 View ,其中包含内部存储在数组中的 x 项。 在初始请求之后,不再有服务器通信,因此所有内容都在浏览器中处理。
在我当前的解决方案中,我为每个 html 缩略图项提供内部数据模型中相应索引的 ID,以便在单击缩略图后我知道要加载哪些数据。
在我尝试实现删除操作之前,我认为这是一个好主意,因此可以删除任何位置的任何项目,也可以拖放缩略图项目。
因此,在我当前的解决方案中,我需要在每次更新后运行每个 html 缩略图项目来调整索引,这不是一个非常好的解决方案。
我不相信我会遇到性能问题,因为缩略图是否包含超过 100 个项目非常值得怀疑,但我想知道是否有更好的解决方案或最佳实践来使其更好。
我无法以任何方式或形式影响数据模型/数组,因此带有 uids 的 map 不是一个选项,也不能使用任何框架,因此需要一个普通的解决方案。
<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();
}
最佳答案
解释
考虑到我们对您正在寻找的确切内容知之甚少,这里有一个简单的方法,您可以通过它简单地处理数据,一些事件和一些渲染,仅使用 native JavaScript。
如果您需要一些文档来理解这段代码,我强烈建议您查看 MDN ,我的意思是我想你大部分都能理解它。正如前面在评论中所述,为了实现这一点,我只是使用 template literals处理 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>
关于javascript - 普通 JS/HTML : best practice to connect html object to internal data-model/array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54539609/