将文本添加到div。新队

时间:2017-06-14 10:25:29

标签: javascript jquery html

我的页面中有一个文本,其中“key”(@ n)为新行,我必须将“key”更改为新行并将此文本添加到我的div中。我找不到如何:

var original= "the text @n to change";
var changed = original.replace(/@n /g, '\n ');

$('#theText').text(changed)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="theText">

</div>

我该怎么做?

3 个答案:

答案 0 :(得分:0)

In HTML normal linebreaks won't work in most cases. Instead use the <br /> tag.

Your code, updated:

var original= "the text @n to change";
var changed = original.replace(/@n /g, '<br />');

$('#theText').html(changed)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="theText">

</div>

You have to use .html() to add the text.

Security note: By using html() your site is potentially threatened by cross site scripting if users can modify the text you want to display.


Alternatively you can also use the <pre> tag or the white-space: pre; css attribte.

答案 1 :(得分:0)

Instead of \n, you can use <br /> and instead of text(), you will have to use html()

var original= "the text @n to change";
var changed = original.replace(/@n /g, '<br /> ');

$('#theText').html(changed)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="theText">

</div>

答案 2 :(得分:0)

我认为,如果你使用.html()和br来实现它会起作用

var original= "the text @n to change";
var changed = original.replace(/@n /g, '<br />');

$('#theText').html(changed)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="theText">

</div>