将一个函数放在另一个函数中不起作用
Placing a function inside of another function not working
我正在尝试让文本一次显示一个字母。我有一个不在函数内部的工作版本。我想将它全部放入一个函数中,但是我无法让它工作。当放入一个函数中时,我遇到了一个问题,它说“.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
循环访问元素即可。
// 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');
<div id="text"></div>
我正在尝试让文本一次显示一个字母。我有一个不在函数内部的工作版本。我想将它全部放入一个函数中,但是我无法让它工作。当放入一个函数中时,我遇到了一个问题,它说“.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
循环访问元素即可。
// 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');
<div id="text"></div>