[英]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 problem
並sleep BETTER
地sleep 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.