JQuery - 延迟和显示文本问题

JQuery - delay and show text issue

下面我得到了一些代码,它应该延迟 2 秒并隐藏上一个跨度并显示下一个跨度,但我似乎无法让它工作。

  <style>
       span{ display:none}
 </style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"><script>
<div id="text"></div>
<script>
    var text = [
        "<span>Sent A blabla</span>",
        "<span>sent B</span><span>sent b bbb cont....</span>",
        "<span>Sent c...</span><span>Sent C2</span><span>sent c3</span>", ];

    var text = text[Math.floor(Math.random() * text.length)];
    jQuery('#text').html(text);
    jQuery('#text').show();
    jQuery('#text span:first').show();


  var delay = 2000;

  jQuery("#text span").each(function() {
      setTimeout( function(){ 
       var el = $(this);
        el.prev().hide();
        el.show();
      }, delay)
      delay += 2000;
  });
</script>

出现此问题是因为您使用了关键字 this

在 for each 语句中,您需要设置一个设置为 $(this) 的变量,然后在超时时引用该变量。示例如下:

  var parent = $(this);
  setTimeout( function(){ 
   var el = parent;
    el.prev().hide();
    el.show();
  }, delay)
  delay += 2000;

JS Fiddle: http://jsfiddle.net/Lykwmfz8/

都在代码注释里:

jQuery(function( $ ){ // FingerSaver: Use $ in the jQuery scope // It's also a DOM ready!

  var delay = 2000;       // You know this one :)
  var $text = $("#text"); // Cache your parent element

  // Elements Array.
  // You  have multiple SPANS per array key
  // (which is odd but OK... here's the array)
  var text = [
    "<span>Sent A blabla</span>",
    "<span>sent B</span><span>sent b bbb cont....</span>",
    "<span>Sent c...</span><span>Sent C2</span><span>sent c3</span>",
  ];

    // Append all SPANs to the #text parent:
    $text.html( text.join("") );
    // All SPANs are now inside #text but are hidden by CSS!

    // Get (cache) all appended SPANs
    var $spans = $text.find("span");

    // OK, how many SPANs we have?
    var tot = $spans.length;
    // (You had 3 array keys, but) 6 SPAN elements :)

    // Start c Counter with a random number
    var c = Math.floor(Math.random() * tot);

    // Create a function that will loop the texts
    (function loop() {
      c += 1;   // Increment counter
      c %= tot; // Reset counter back to 0 on reminder
      $spans.fadeOut(500).eq( c ).stop().fadeIn(500);
      setTimeout(loop, delay);
    }()); // Start!

});
#text span{
  position:absolute;
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text"></div>

如果您想保留多个 SPAN 元素的集合并显示为 GROUPS,那么您需要做的就是将数组键中的每个 SPAN 包装到 parent 包装器中,这样做也是一样的如上所述,只是,不是在 SPANS 上操作,而是在他们的 parent 上操作。由于您在问题中没有解释得很好,以上就是我目前能给您的全部内容。