我无法让setTimeout事件适用于此代码。我已尝试过各种配置,但没有运气。有人能告诉我我做错了什么吗?
我试图一次打印出“lorem ipsum”一个字符,但我想在它开始前等待几秒钟。
setTimeout(
(function ($) {
$.fn.writeText = function (content) {
var contentArray = content.split(""),
current = 0,
elem = this;
setInterval(function () {
if (current < contentArray.length) {
elem.text(elem.text() + contentArray[current++]);
}
}, 40);
};
})(jQuery);
$("#description").writeText("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate.");
, 3000);
解决方案:
这是工作代码。问题是整个插件被包装在超时中。解决方案是仅包装实现插件的行。谢谢@adeno的答案!
(function ($) {
$.fn.writeText = function (content) {
var contentArray = content.split(""),
current = 0,
elem = this;
setInterval(function () {
if (current < contentArray.length) {
elem.text(elem.text() + contentArray[current++]);
}
}, 40);
};
})(jQuery);
setTimeout(function () {
$("#description").writeText("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate.");
}, 3000);
答案 0 :(得分:3)
setTimeout具有以下签名:
setTimeout(function, timeout_in_ms);
在您的代码中,您有:
setTimeout(
statement;
statement;
statement;
, timeout_in_ms
);
所以它甚至在语法上都不正确