防止自定义 jquery 函数在同时运行时合并联接

Preventing a custom jquery function from merging joining when running at the same time

本文关键字:运行时 合并 自定义 jquery 函数      更新时间:2023-09-26

我正在尝试编写一个简单的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>