【发布时间】:2017-03-16 12:07:10
【问题描述】:
我正在使用来自this answer on SO 的打字机效果,目的是输入第一个 div,然后输入第二个 div(当第一个 div 完成输入时)。
<div class="text">
Lorem ipsum dolor sit amet...
</div>
<div class="text">
Cras eros augue, tempor...
</div>
JS:
// Create typewrite function as jQuery plugin:
// (From https://stackoverflow.com/a/22266737/3217306)
$.fn.typeText = function() {
var keystrokeDelay = 10,
self = this,
str = self.html(),
i = 0,
isTag,
text;
self.html("");
(function type() {
text = str.slice(0, ++i);
if (text == str) {
console.log("completed typing");
return;
}
self.html(text);
var char = text.slice(-1);
if (char == "<") {
isTag = true;
}
if (char == ">") {
isTag = false;
}
if (isTag) {
return type();
}
setTimeout(type, keystrokeDelay);
} ());
};
var textElements = $(".text");
// For each div.text, type them out
textElements.each(function() {
$(this).typeText();
});
问题是,两者同时输入。我已经尝试了很多涉及承诺、回调等的不同方法,但我无法让它们在这种情况下工作。
【问题讨论】:
-
尝试使用递归函数而不是
each
标签: javascript jquery asynchronous callback promise