jQuery 每个循环中一个接一个的顺序函数

jQuery sequential functions one after the other in a each loop

我知道这个话题已经在几个帖子中讨论过,但我似乎无法为我的特定用例做这件事。

所以我需要模拟一个接一个地在页面上输入值。用户只是坐下来观看 - 但本质上我需要的是加载,第一个输入集中 > 逐个字母输入一个值,然后移动到下一个输入以对其值执行相同的操作。

这里是 fiddle 到目前为止我的代码的意思:https://codepen.io/samwoodchs/pen/WNxYmPj

$(document).ready(function(){

$('.typein').each(function(i, el) {
    var value = $(this).data('value');

    $(this).focus();
    $(this).val(''); //clear
    typeText($(this), value, 150, 0);

});

function typeText(item, text, delay, i) {
    $(item).val($(item).val() + text.charAt(i))
        .delay(delay)
        .promise()
        .done(function() {
            if(i<text.length) {
                i++;
                typeText(item, text, delay, i);  
            }
        });       
}

});

我在每个循环 jQuery 中使用它,但似乎无法让它按顺序工作而不是同时工作。我猜我需要使用队列或承诺功能,但不确定如何使用。在每个循环中执行此操作的原因是不同的页面具有不同的输入量,我想找到一个解决方案来通过选择器(class 名称)而不是 maunally 来解决这个问题。

如有任何帮助,我们将不胜感激

您可以使用 Promises 链接一个有序的函数数组,如下所示:

$(document).ready(function () {

    const delay = 150;
    $('.typein').data('value', 'other value');

    const functions = $('.typein').map((_, item) => typeText(item)).get();
    chainAndExecDelayedFunctions(functions, delay);

    function typeText(item) {
        return [
            () => {
                $(item).focus();
                $(item).val('');
            }
        ].concat($(item).data('value').split('').map(char => () => {
                $(item).val($(item).val() + char);
            }));
    }

    function chainAndExecDelayedFunctions(functions, delay) {
        functions.reduce((acc, cur) => {
            return acc.then(() => new Promise(resolve => setTimeout(() => {
                        resolve();
                        cur();
                    }, delay)));
        }, Promise.resolve());
    }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="typein" value="initial value">
<input class="typein" value="initial value">
<input class="typein" value="initial value">
<input class="typein" value="initial value">
<input class="typein" value="initial value">
<input class="typein" value="initial value">
<input class="typein" value="initial value">
<input class="typein" value="initial value">