简体   繁体   English

HTML文本到换行符的jQuery

[英]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 我有一个php函数,该函数在末尾生成一些带有“ \\ n \\ r”的文本
  2. The output is generated in a html div, which is hidden 输出是在html div中生成的,已隐藏
  3. JQuery takes the text of the div with innerText jQuery使用innerText获取div的文本
  4. Writes it in a other div 将其写入另一个div

That's what i do in the moment. 那是我目前的工作。 The line break in php has no effect to the "end div". php中的换行符对“ end div”无效。

How can i get the line break at the end div? 我如何在末尾div换行?

Regards 问候

EDIT: With a <br> in my php function an alert works fine. 编辑:在我的PHP函数中使用<br>警报可以正常工作。 So the failure is at point 4. 因此故障发生在第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. 您可以使用javascript String.replace方法将\\n\\r更改为<br>标记,以便浏览器将其呈现。

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. 您可以看到控制台和警报窗口像对待文本编辑器一样对待这些特殊字符,但是它们不会在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! 有趣的事情:当我从JS将文本写到textarea时,它起作用了!

So the problem seems to be the <div> . 因此,问题似乎出在<div> I tryed with a random tag like <random> , it's not working. 我尝试使用<random>类的随机标记,此标记无效。

Any ideas what is wrong? 任何想法有什么问题吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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