最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

setinterval - JavaScript line break issue - Stack Overflow

programmeradmin0浏览0评论

In this snippet, when 'FirstText' is written, then rest of first line is skipped. Then 'SecText' is written on the 2nd line:

<pre>
 <script>
  function text(){
  document.write("FirstText \n SecText");
  }
  text();
 </script>
</pre>

But when I use setInterval() on this function, words are written next to each other (lines are not skipped).

Any suggestions?

In this snippet, when 'FirstText' is written, then rest of first line is skipped. Then 'SecText' is written on the 2nd line:

<pre>
 <script>
  function text(){
  document.write("FirstText \n SecText");
  }
  text();
 </script>
</pre>

But when I use setInterval() on this function, words are written next to each other (lines are not skipped).

Any suggestions?

Share Improve this question edited Jan 8, 2017 at 20:25 Kishore Bandi 5,7212 gold badges34 silver badges54 bronze badges asked Jun 2, 2013 at 19:18 MattMoulsonMattMoulson 451 gold badge1 silver badge4 bronze badges 2
  • Do you need another \n after SecText? – Peter de Rivaz Commented Jun 2, 2013 at 19:20
  • you need a <br> : document.write("FirstText <br /> SecText"); – Utopik Commented Jun 2, 2013 at 19:38
Add a ment  | 

2 Answers 2

Reset to default 8

You're seeing \n create a new line because you're inside a <pre /> tag; normally you have to use a <br /> to see a similar new line outside of <pre />.

When you call document.write before the page has finished loaded, the output is entered inplace; so you'll see your FirstText \n SecText written within the <pre />.

However, when it's called after the page has loaded (within setInterval), the existing page is cleared before the result is written; hence <pre /> is being removed, and you're not seeing your new line any more.

As you're not closing the document using document.close(), successive calls to document.write in your setInterval are adding to the document stream opened by the first iteration of setInterval.

You can fix this by using a <br /> rather than \n;

     <script>
      function text(){
      document.write("FirstText <br /> SecText <br />");
      }

      setInterval(text, 1000);
     </script>

For more info, see https://developer.mozilla/en-US/docs/Web/API/document.write and document.write clears page

try this:

document.write("FirstText <br /> SecText <br/>");

working example:

http://jsbin./oyolod/4/

发布评论

评论列表(0)

  1. 暂无评论