Agn*_*ane 8 html javascript jquery
我想一次又一次地使用数组中的项替换段落的内容.当我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();
});
});
Run Code Online (Sandbox Code Playgroud)
在等待()函数:
function wait(_timeframe)
{
var final = 0;
var timeframe = new Date(_timeframe);
var initial = Date.now();
final = initial + _timeframe;
while (Date.now() < final) { };
}
Run Code Online (Sandbox Code Playgroud)
HTML代码:
<p>Text to be replaced here</p>
Run Code Online (Sandbox Code Playgroud)
使用setInterval()方法检查下一个示例,它将<p>每N秒替换元素的文本,并在到达结尾时循环回到数组的开头.
另外,我添加了一个按钮,向您展示如何使用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);
});
});Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper {max-height:50% !important;}
.as-console {background-color:black !important;color:lime;}
p {
background: skyblue;
text-align: center;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
问题是,您等待的函数会阻塞用户界面。相反,您应该使用window.setTimeout,它会在特定时间后调用回调。
你可以尝试这样的方法来解决你的问题
$(function() {
var words = ["Lorem", "ipsum", "dolor"];
var $element = $("p");
// callback function
var f = function() {
$element.html(words.shift());
if (words.length > 0) {
window.setTimeout(f, 1000);
}
}
// initial call
f();
};
Run Code Online (Sandbox Code Playgroud)