简体   繁体   English

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

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

I wanted to break the one string in the set of array elements. 我想破坏一组数组元素中的一个字符串。 The output will be display with a time interval. 将以时间间隔显示输出。 Javascript: 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>

The output is: solve the problem sleep BETTER. 输出为:解决更好的睡眠问题。 But I need something like this: solve the problem (In new line) sleep BETTER. 但是我需要这样:解决问题(换行),睡得更好。

Html: HTML:

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

I need to display the caption with a new line. 我需要用新行显示标题。

Thank you! 谢谢!

Instead of simply overwriting the text content with caption.innerHTML = text[i] , you'll want to append to the content with += . 与其简单地使用caption.innerHTML = text[i]覆盖文本内容, caption.innerHTML = text[i]使用+= 附加到内容上。 To output solve the problem and sleep BETTER onto new lines, you'll first want to separate and them out in the array, and then add an HTML line break ( <br /> ) before outputting the new text: 要输出以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 you don't want the to repeat, simply set the functionality inside of an if statement that checks if (i < text.length) : 如果您不想重复该操作,只需在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