【问题标题】:How to break the strings into new line which are declared in array? Javascript/Jquery如何将字符串分成数组中声明的新行? Javascript/Jquery
【发布时间】:2019-03-12 13:00:43
【问题描述】:

我想打破一组数组元素中的一个字符串。 输出将以时间间隔显示。 Javascript:

    <script type="text/javascript"> 
    var caption= document.getElementById('caption');
    var text=['Hey there please help me','solve the problem sleep BETTER.'];
                    function display(i){
                    if(i >= text.length){
                       i = 0;
                       }
                    caption.innerHTML = text[i];
                    setTimeout(function(){
                      display(i + 1)
                     }, 6000)

                   }
                   display(0)
     </script>

输出是:解决问题睡眠更好。 但我需要这样的东西:解决问题(在新行中) 睡得更好。

HTML:

<div class= "content" >
h1><span id="caption"> </span></h1> 
</div>

我需要用新行显示标题。

谢谢!

【问题讨论】:

    标签: javascript jquery html arrays string


    【解决方案1】:

    您需要追加到带有+= 的内容,而不是简单地用caption.innerHTML = text[i] 覆盖文本内容。要将solve the problemsleep BETTER 输出到新行,您首先需要在数组中将它们分开,然后在输出新文本之前添加HTML 换行符(&lt;br /&gt;):

    var caption = document.getElementById('caption');
    var text = ['Hey there please help me', 'solve the problem', 'sleep BETTER.'];
    
    function display(i) {
      if (i >= text.length) {
        i = 0;
      }
      caption.innerHTML += "<br />" + text[i];
      setTimeout(function() {
        display(i + 1)
      }, 6000)
    }
    
    display(0)
    <div class="content">
      <h1><span id="caption"> </span></h1>
    </div>

    如果您不想重复,只需在检查if (i &lt; text.length)if 语句中设置功能即可:

    var caption = document.getElementById('caption');
    var text = ['Hey there please help me', 'solve the problem', 'sleep BETTER.'];
    
    function display(i) {
      if (i < text.length) {
        caption.innerHTML += "<br />" + text[i];
        setTimeout(function() {
          display(i + 1)
        }, 6000)
      }
    }
    
    display(0)
    <div class="content">
      <h1><span id="caption"> </span></h1>
    </div>

    【讨论】:

    • 谢谢,我需要覆盖字幕。我不想一一显示。**你有更好的解决方案吗? **
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    相关资源
    最近更新 更多