javascript - 使用 each() 方法动画输入代码

标签 javascript jquery html

我正在尝试使用 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/

相关文章:

Javascript:对象如何存储对另一个对象方法的引用,并将其称为 "remotely"?

javascript - 如何在圆圈范围内反弹对象?

javascript - 网站无法正常工作的向上滚动按钮

javascript - 简单 CoffeeScript 和 jQuery 事件的奇怪问题

css - Chrome 打印网站,缺少布局选项

jQuery UI 按钮和 anchor 标记

javascript - 下划线 bindAll,显式方法命名

jquery 单击处理程序将单击对象的属性传递给函数?

php - 返回正确的 JSON 响应

javascript - 改进图像加载时间