首页 > 解决方案 > 如何一次又一次地动态替换文本

问题描述

我想一次又一次地使用数组中的项目动态替换段落的内容。当我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>

标签: javascriptjqueryhtml

解决方案


对于这种方法,您可以使用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>


推荐阅读