簡體   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