如何一次又一次地动态替换文本

时间:2018-12-03 21:15:13

标签: javascript jquery html

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

wait()函数:

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>

2 个答案:

答案 0 :(得分:8)

使用setInterval()方法检查下一个示例,它将每N秒替换<p>元素的文本,并在到达数组末尾时循环回到数组的开头。

此外,我添加了一个按钮,向您展示如何使用clearInterval()方法停止执行此过程(以防万一您需要了解它的情况)。

$(document).ready(function()
 {
    // Define the time interval between executions (in milliseconds).
    var _ivalTime = 3000;

    var _strng = "Lorem ipsum dolor sit amet";
    var _array = _strng.split(' ');
    var _idx = 0;

    var ival = setInterval(function()
    {
        var item = _array[_idx++];
        console.log(item);
        $('p').html(item);

        // Check the restart (loop back) condition.

        _idx = (_idx >= _array.length) ? 0 : _idx;
    },
    _ivalTime);
    
    // Register listener on the click event of stop button.
    
    $("#btnStop").click(function()
    {
        clearInterval(ival);
    });
});
.as-console-wrapper {
    max-height: 50% !important;
}

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>

答案 1 :(得分:4)

问题是,您等待函数阻止ui。相反,您应该使用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();
};
相关问题