【问题标题】:Placing a function inside of another function not working将一个函数放在另一个函数中不起作用
【发布时间】:2021-10-24 06:47:50
【问题描述】:

我试图让文本一次显示一个字母。我有一个不在函数内部的工作版本。我想将它全部放入一个函数中,但是我无法让它工作。当放入一个函数时,我遇到了一个问题,它说“.split”不是一个函数。

函数外的工作版本

let text = 'Lorem ipsum dolor sit, amet consectetur adipisicing elit.'

const textArray = text.split('');
let loopTimer;

const frameLooper = () => {
    textArray.length > 0 ? document.querySelector('#text').innerHTML += textArray.shift() : clearTimeout(loopTimer);
    loopTimer = setTimeout('frameLooper()', 30);
}

frameLooper()

函数内部(不工作)

    let dialog = (text) => {
        let textArray = text.split('');
        return textArray;
    }
    
    let loopTimer
    
    const frameLooper = (text) => {
        let array = dialog(text)
        array.length > 0 ? document.querySelector('#text').innerHTML += array.shift() : clearTimeout(loopTimer);
        loopTimer = setTimeout('frameLooper()', 30);
    }
    
    frameLooper(dialog('This is a test'))

如果需要,这里是 HTML:

        <p id="text" class="text-red-200"></p>

    </div>

【问题讨论】:

  • setTimeout('frameLooper()' 你没有传递参数,但是函数需要一个参数
  • 避免将字符串传递给setTimeout

标签: javascript html closures


【解决方案1】:

我不会为操作数组而烦恼 - 只需从 setTimeout 循环访问元素即可。

// Cache the element
const div = document.querySelector('#text');

function frameLooper(str) {

  // Split the string
  const arr = str.split('');

  // Create a small loop for the `setTimeout` to call
  // Set the index to 0
  function loop(i = 0) {

    // If the index is less than the array length
    // add a letter from the array
    if (i < arr.length) div.textContent += arr[i];

    // Otherwise increase the index, and run the loop again
    setTimeout(loop, 100, ++i);

  }

  loop();

}

// Pass in the string
frameLooper('This is a test');
&lt;div id="text"&gt;&lt;/div&gt;

【讨论】:

  • 谢谢。你能够解决我的问题。非常感激!另外,我注意到我被否决了。我在帖子中做错了什么吗? (为了记录,我尝试了几个小时的研究,但直到你的帖子才找到解决方案)。我对 JavaScript 很陌生,所以我还在学习。
  • 你写了一个非常好的问题 IMO。很抱歉你被否决了。你试图调试你的代码,你寻求帮助——但最重要的是你投入了工作。我很高兴我能提供帮助。欢迎来到 SO。这个网站可能有点善变。希望你的编码顺利。
  • 啊,我明白了。好吧,至少当时不是我在帖子上做错了什么。再次感谢!祝你有个好的一天! (我会投票赞成你的帖子,但我还不允许它说。我至少能够接受它作为答案)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 2019-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多