jquery - UI 仅在循环完成后更新
问题描述
我正在html()
循环使用。显示仅在循环结束时更新。我console.log
之后添加,我在控制台中看到了日志。如果我添加一个,alert
我可以看到显示发生变化。
for (i = 0; i < 25; i++) {
$("#selector").html(" Occurences " + i);
console.log(" Occurences " + i);
//alert("something");
wait(200);
}
function wait(ms) {
var start = new Date().getTime();
var end = start;
while (end < start + ms) {
end = new Date().getTime();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="selector">Test</div>
解决方案
这是预期的行为,因为for
循环while
会在处理 UI 时阻止 UI 更新。
假设从代码的上下文中您尝试创建一个显示在 UI 中的增量计数器,您可以使用 jQuery 的animate()
方法:
$({
Counter: 0
}).animate({
Counter: 25
}, {
duration: 5000, // 25 iterations * 200ms delay
easing: 'linear',
step: n => $('#my_selector').text(`Occurences: ${Math.ceil(n)}`)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="my_selector"></span>
推荐阅读
- javascript - pdfjs在包含非标准字符时无法查看PDF
- javascript - react-chart-js-2 - 在标签上添加标点符号?
- vue.js - Vuex 状态未设置为 getter
- unity3d - 为什么 hit.point 在同一光线投射中重置为 0,0,0?
- python - 试图用 txt 数据创建一个列表数组,Python
- json - 尽管所有其他对象都可以正常工作,但每个循环的车把都无法正常工作
- wordpress - WordPress 的 Astra Pro 主题为什么不显示徽标?
- c++ - c ++试图在元组向量上使用带有比较函数的lower_bound但错误:没有匹配函数调用'get <0>(const std :: tuple)'
- networking - Packer Tracer:WLAN 配置与多个 VLAN
- syntax-error - Sieve 语言语法错误帮助“如果附近有分号的标识符”