我正在尝试使用 JQuery 的 each() 方法在多个代码块上设置动画,但我不断收到此错误:
未捕获的类型错误:无法调用未定义的方法“createDocumentFragment”
Check out some example code in this Fiddle...
为了您的方便,下面列出了 JS:
$('.typeanimator').each(function(index) {
console.log(index);
var codeBlock = $(this).text();
var done;
var blockLength = codeBlock.length;
var charCounter = 0;
$(this).text('|');
(function typeAnimator() {
var typingSimulator = Math.round(Math.random() * (200));
done = setTimeout(function() {
console.log("Le print.");
charCounter++;
var typeSection = codeBlock.substring(0, charCounter);
$(this).text(typeSection + '|');
typeAnimator();
if (charCounter == blockLength) {
$(this).text($(this).text().slice(0, -1));
clearTimeout(done);
}
}, typingSimulator);
}());
});
最佳答案
问题出在 typeAnimator
函数中对 $(this)
的使用。您实际上想从父函数引用 this
,但您得到的是完全不同的 this
。因此,使用一个临时变量来存储 $(this)
$('.typeanimator').each(function(index) {
...
var self = $(this);
self.text('|');
(function typeAnimator() {
var typingSimulator = Math.round(Math.random() * (200));
done = setTimeout(function() {
...
self.text(typeSection + '|');
typeAnimator();
if (charCounter == blockLength) {
self.text(self.text().slice(0, -1));
clearTimeout(done);
}
}, typingSimulator);
}());
});
已更新 fiddle
关于javascript - 使用 each() 方法动画输入代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20606018/