如何保留换行符 [英] How to preserve a line break

查看:123
本文介绍了如何保留换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

换行符和回车...必须是编码中最复杂的部分. (对我来说)

将此代码保存在页面中(来自存储为This from Ricardo\nAnd also a test\nRent 3000.00的数据库):

<td title="This from Ricard
And also a test
Rent 3000.00" style="width:198px;text-align:left">....</td>

然后使用它来获取带有'hidden'\ n的title属性.

var v = $('#'+i).parent().attr('title');        // i = id of <span> child of <td>

一路走来,换行符丢失了,并在文本输入框中使用了变量v:

This from RicardAnd also a testRent 3000.00

如何保存\n's并使其外观如下所示?

解决方案

换行符仍然存在,只是浏览器尝试呈现它们.

如果您仍然想看到"\ n",请尝试以下操作:

var v = $('td:first-of-type').attr('title').replace(/\n/g, "\\n");

否则,如果您不想看到"\ n",而是看到换行符,则可以这样操作:

var v = $('td:first-of-type').attr('title').replace(/\n/g, "<br/>");

选中此 JSBin

Line breaks and carriage returns... Must be the most complicated part of coding. (for me)

Have this code in a page (which came from database stored as This from Ricardo\nAnd also a test\nRent 3000.00):

<td title="This from Ricard
And also a test
Rent 3000.00" style="width:198px;text-align:left">....</td>

Then use this to get the title attribute with 'hidden' \n's

var v = $('#'+i).parent().attr('title');        // i = id of <span> child of <td>

Along the way, the line breaks get lost and using the variable v into a text input box:

This from RicardAnd also a testRent 3000.00

What does it take to preserve the \n's and have this look instead like below?

解决方案

The line breaks are still there, it is just that the browser tries to render them.

If you still want to see the "\n" try this:

var v = $('td:first-of-type').attr('title').replace(/\n/g, "\\n");

Else, if what you want is NOT to see the "\n" and instead see the line breaks, you could do it this way:

var v = $('td:first-of-type').attr('title').replace(/\n/g, "<br/>");

Check this JSBin

这篇关于如何保留换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆