Javascript 使用回调进行排序
我有几个用于对页面上的当前元素进行排序的链接。
功能:
- A - 使用数组排序的单击处理程序
- B - 根据排序的数组显示元素。
排序甚至可能需要 2 秒,所以我想向用户显示一些反馈。
我考虑过将链接文本更改为“进行中..”或类似的内容。
在乐趣中 A 存储旧链接文本并将其更改为“进行中”并将另一个函数传递给 B 我在显示元素之后调用它来显示链接的旧文本,但它不起作用。
在调试器中,链接文本已更改,但我始终只能看到旧文本。
我如何为此创建有效的回调?
我看到网站有类似的排序,但也没有向用户提供任何反馈。
这可以用javascript来做吗?或者反馈只能在ajax请求时显示?
I have several links for sorting current elements on page.
Functions:
- A - click handler with array sort
- B - display elements according to sorted array.
Sorting can take even 2 seconds, so I want to display some feedback to user.
I thought about change link text to 'In progress..' or something like that.
In fun A store old link text and change it to 'In progress' and pass another function to B
that I invoke after display elements to show old text of link, but it just doesn't work.
In debugger link text is changed, but I can see only old text all the time.
How can I create valid callback for this?
I see websites with similar sorting and without any feedback to user too.
Is this possible to do with javascript? Or feedback can be display only on ajax request?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题很可能是您正在运行完全同步代码。
在您启动的任何函数完成之前,DOM 不会更新(即使您在长时间运行的计算之前更新 DOM)。
下面是一个长时间运行计算的示例,该计算会阻止 DOM 立即更新。 (单击顶部的“渲染”按钮即可正确查看示例。)
请注意,示例中出现了
“正在开始...等待几秒钟。”
文本立即执行,并且不会被长时间运行的计算所阻塞。但“Updated”
文本需要 3 秒才会出现。这样做的原因是因为我首先将
"Starting..."
添加到 DOM,然后将其余代码包装在setTimeout
中。这允许 DOM 立即更新“Starting...”,但setTimeout
内的其余代码是同步的,因此在该代码完成之前 DOM 不会再次更新。因此,您的解决方案可以是使用
"In Progress..."
更新文本,然后将其余代码包装在setTimeout()
中,以允许 DOM立即更新您的进度消息。The issue is most likely that you're running entirely synchronous code.
The DOM does not update until whatever function(s) you've started have completed (even if you update the DOM before the long running calculation).
Here's an example of a long running calculation that prevents the DOM from updating immediately. (Click the "Render" button at the top to see the example properly.)
Notice in the example that the
"Starting... Wait a few seconds."
text appears immediately, and is not blocked by the long running calculation. But the"Updated"
text takes 3 seconds to appear.The reason for this is because I added the
"Starting..."
to the DOM first, then wrapped the rest of the code in asetTimeout
. This allowed the DOM to update immediately for"Starting..."
, but the rest of the code within thesetTimeout
is synchronous, so the DOM won't update again until that code is complete.So your solution can be to update the text with
"In progress..."
, then wrap the rest of the code in asetTimeout()
in order to allow the DOM to update immediately with your progress message.