防止自定义 jquery 函数在同时运行时合并联接
Preventing a custom jquery function from merging joining when running at the same time
我正在尝试编写一个简单的jquery"addon",为我键入文本,就像打字机一样。
这是我到目前为止想出的:
jQuery.fn.typer=function(speed){
typed = this;
theText = typed.text().split('');
typed.text("");
$.each(theText, function(index, value){
setTimeout(function(){
typed.append(value);
},speed*index);
});
return;
};
$("#p0").typer(50);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='p0'>This text will appear at the speed: 50</p>
这工作得很好,直到我尝试让它一次输入两个句子。
jQuery.fn.typer=function(speed){
typed = this;
theText = typed.text().split('');
typed.text("");
$.each(theText, function(index, value){
setTimeout(function(){
typed.append(value);
},speed*index);
});
return;
};
$("#p0").typer(50);
$("#p1").typer(100);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='p0'>This text will appear at the speed: 50</p><br />
<p id='p1'>This text will appear at the speed: 100</p>
我得到的结果是:速度:100
关于如何阻止这种情况发生的任何线索?
提前谢谢。
声明变量而不使用 var
关键字会将变量置于全局范围内。有关更多详细信息,请参阅此问题。
因此,两个实例共享变量并导致您在上面看到的胡言乱语。
jQuery.fn.typer=function(speed){
var typed = this;
var theText = typed.text().split('');
typed.text("");
$.each(theText, function(index, value){
setTimeout(function(){
typed.append(value);
},speed*index);
});
return;
};
$("#p0").typer(50);
$("#p1").typer(100);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='p0'>This text will appear at the speed: 50</p><br />
<p id='p1'>This text will appear at the speed: 100</p>
相关文章:
- 使用压缩的JavaScript文件(不是运行时压缩)
- 如何在运行时在angular 2中加载外部js脚本
- JavaScript错误:Microsoft JScript运行时错误:应为对象
- Google 脚本:用于创建日历活动的脚本运行时不会出错,但不会执行任何操作
- http.listen()在运行时接受终端命令
- 自定义运行时Can'在谷歌应用引擎中看不到我的自定义日志
- 实现比较方法的最佳实践是什么;s的比较类型是在运行时选择的
- JavaScript运行时是如何工作的
- 在运行时创建元素时移到一边时出错
- 如何在运行时在HTML5画布中绘制正方形
- 如何在运行时使用javascript隐藏图像
- 在运行时使用jquery准备表体会导致设计问题
- 使用主题运行时portlet liferay时出现Javascript错误
- JavaScript运行时事件循环现有技术
- Appcelerator Titanium:在运行时下载并解释JavaScript代码
- angularjs ng点击运行时标记不起作用
- 在函数运行时显示对话
- 如何在javascript中在运行时获取对象/数组
- 变量在运行时未定义,但在使用调试器时定义
- 防止自定义 jquery 函数在同时运行时合并联接