繁体   English   中英

如何将字符串拆分为在数组中声明的新行? Javascript / jQuery

[英]How to break the strings into new line which are declared in array? Javascript/Jquery

我想破坏一组数组元素中的一个字符串。 将以时间间隔显示输出。 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>

我需要用新行显示标题。

谢谢!

与其简单地使用caption.innerHTML = text[i]覆盖文本内容, caption.innerHTML = text[i]使用+= 附加到内容上。 要输出以solve the problemsleep BETTERsleep BETTER在新行上,您首先需要将它们分开并放在数组中,然后在输出新文本之前添加HTML换行符( <br /> ):

 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语句中设置功能,以检查if (i < text.length)

 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM