简体   繁体   中英

Html text to JQuery with line break

following example:

  1. I got a php function which generates me some text with "\\n\\r" at the end
  2. The output is generated in a html div, which is hidden
  3. JQuery takes the text of the div with innerText
  4. Writes it in a other div

That's what i do in the moment. The line break in php has no effect to the "end div".

How can i get the line break at the end div?

Regards

EDIT: With a <br> in my php function an alert works fine. So the failure is at point 4.

 var text = document.getElementById("statistiktextdiv").innerText; $jq( "#statistiktext" ).text(text); 
 <div id="statistiktext"></div> function showsomething(){ for($i = 0; $i < count($statistik); $i++){ echo $something[$i]['number'] . "<br>"; } } ?> <div id="statistiktextdiv" style="visibility: hidden;"><?php showsomething(); ?></div> 

You can use the javascript String.replace method to change the \\n\\r to a <br> tag so the browser will render it.

alteredText = originalText.replace( '\n\r', '<br>' );

You can see that the console and alert windows treat these special characters the way a text editor does, but they are not rendered as breaks in html.

 originalText = "line 1\\n\\r\\line 2"; alteredText = originalText.replace( '\\n\\r', '<br>' ); console.log( originalText ); console.log( '---------' ); console.log( alteredText ); $('body').append( originalText ); $('body').append( '<hr>' ); $('body').append( alteredText ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Something interessting: When i write the text from JS to an textarea, its working!

So the problem seems to be the <div> . I tryed with a random tag like <random> , it's not working.

Any ideas what is wrong?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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