将元素插入 DOM,基于时间戳的位置
我有一个带有“更新”数组的 JSON 对象,其中每个“更新”由一个时间戳和一条消息组成:
updates : {
{
timestamp : 1329505671,
text : 'test1'
},
{
timestamp : 1329505783,
text : 'test2'
}
}
使用 jQuery,我将它们解析为 DOM 元素,并按照接收顺序将它们插入到同一级别。它们是根据我在 AJAX 调用中的 SQL 查询进行预排序的。
现在,我有一个重复的 ajax 调用来检查新的更新。如果发现更新,则需要将其插入到 DOM 中的适当位置。
我不能假设这些更新将始终是列表中的最新更新,因此,我需要一种方法来查找在哪个 DOM 更新之后插入新更新。
我本来计划创建一个 Map
之类的(在 Javascript 中为 updates[timestamp] = DOMUpdate
)。
不过,这个计划有几个缺陷:
- 我必须找到/创建一个快速的二进制搜索算法来查找 将更新放在哪个时间戳之后。
- 我不能有重复的时间戳。
所以我的问题是是否有其他人做过类似的事情,如果是的话,你是如何处理的?如果我有任何不清楚的地方,请告诉我。
I have a JSON object with an array of "updates", where each "update" consists of a timestamp and a message:
updates : {
{
timestamp : 1329505671,
text : 'test1'
},
{
timestamp : 1329505783,
text : 'test2'
}
}
Using jQuery, I parse these into DOM elements and insert them at the same level, in the order they were received. They are presorted based on my SQL query in the AJAX call.
Now, I have a recurring ajax call that checks for new updates. If an update is found, it needs to insert it into the DOM, in the appropriate position.
I cannot assume that these updates will always be the newest update in the list, so, I need a way to find which DOM update to insert the new update after.
I had planned on creating a Map<int, DOMUpdate>
of sorts (updates[timestamp] = DOMUpdate
in Javascript).
There are a couple flaws with this plan, though:
- I'd have to find/create a fast binary search algorithm for finding
which timestamp to put the update after. - I couldn't have duplicate timestamps.
So my question is if anyone else has done something similar, and if so, how did you approach it? Please let me know if I'm being unclear in any way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需找到第一个时间戳大于它的元素并将其附加到该元素之前即可。如果没有找到,则它是最新的,应根据您发布它们的顺序(最新的第一个或最后一个)附加在开始/结束处。
显然这只是一个概念,您需要修改它以适应您的代码/要求。
编辑:
如果您将数据存储在对象数组中,然后在收到更多对象时将对象添加到该数组中,则可以根据时间戳对该数组进行排序,然后在排序后根据索引附加新对象。您必须向新接收的对象添加一个属性,然后在循环遍历所有对象时删除该属性,并仅附加具有该属性的对象。
Just find the first element that has a timestamp that is greater than it and append it before that element. If none are found, it is the newest and should be appended at the start/end depending on the order you are posting them(newest first or last).
Obviously this is just a concept, you will need to modify it to fit your code/requirements.
Edit:
If you stored your data in an array of objects, and then added objects to that array as more were received, you could sort that array on the timestamp and then append the new objects based on the index after sorting. You would have to add a property to the newly received objects, and then remove that property as you loop through all of the objects and append only those that have that property.