javascript - 如何一次又一次地动态替换文本
问题描述
我想一次又一次地使用数组中的项目动态替换段落的内容。当我console.log()
用来检查结果时,输出很好。但它并没有按预期替换段落上的内容,只是在迭代完成时显示最后一个单词。
这是我创建和迭代数组的代码:
$(document).ready(function()
{
var _strng = "Lorem ipsum dolor sit amet";
var _array = new Array();
_array = _strng.split(' ');
jQuery.each(_array, function(index,item)
{
console.log(item); // Works fine
$('p').html(item); // Only shows the last word when the iteration is over
wait(1000); // Custom function
console.clear();
});
});
等待()函数:
function wait(_timeframe)
{
var final = 0;
var timeframe = new Date(_timeframe);
var initial = Date.now();
final = initial + _timeframe;
while (Date.now() < final) { };
}
HTML代码:
<p>Text to be replaced here</p>
解决方案
对于这种方法,您可以使用setInterval()方法。在下一个示例中,我们使用它<p>
每秒替换元素的文本,N
当它到达末尾时循环回到数组的开头。
此外,还有一个button
展示如何使用clearInterval()方法停止执行此过程(以防万一您需要了解它)。
$(document).ready(function()
{
var _str = "Lorem ipsum dolor sit amet";
var _array = _str.split(' ');
var _idx = 0;
// Define the time interval between executions (in milliseconds).
var _ivalTime = 3000;
// Define the method that will change the text.
var changeText = function()
{
var item = _array[_idx++];
console.log(item);
$('p').html(item);
// Check the restart (loop back) condition.
_idx = (_idx >= _array.length) ? 0 : _idx;
};
// Start the procedure to change text.
var ival = setInterval(changeText, _ivalTime);
// Register listener on the click event of stop button.
$("#btnStop").click(function()
{
clearInterval(ival);
});
});
.as-console-wrapper {max-height:50% !important;}
.as-console {background-color:black !important;color:lime;}
p {
background: skyblue;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>INITIAL TEXT...</p>
<br>
<button id="btnStop" type="button">Stop</button>
推荐阅读
- python - Calling Python code from TCL and checking its return value
- xero-api - Xero 的 OAuth 2.0 支持哪些 OAuth2.0 流程?
- jquery - Bootstrap 模态对话框是通过 JQuery 打开时自动滚动浏览器到顶部
- django - 成功消息在基于 Django 类的 Createview 中不起作用
- laravel - production.ERROR:从空值创建默认对象 {"exception":"[object]
- c# - 项目“ClassLibrary1.csproj”以“netstandard2.1”为目标。它不能被以 '.NETFramework,Version=v4.8' 为目标的项目引用
- node.js - 无法从 nodejs(express) 简单应用程序连接到 mongodb Atlas 集群
- vb.net - PropertyGrid 值变化
- c# - Azure Kinect 传感器 SDK - 用于图像捕获的 C# 包装器缺少“缓冲区”?
- intellij-idea - JetBrains Toolbox 在同一窗口中打开项目