使用JavaScript写入HTML时的换行问题 [英] Newline problem when writing to HTML using JavaScript
问题描述
我正在使用常规文本框作为文本输入,用户可以在其中记录他们的评论。然后我使用JQuery和JSON将数据发送到服务器,然后将其插入数据库。
I'm using regular textbox as a text input where the users wrties their comments. I then use JQuery and JSON to send data to the server and then insert it into the database.
当我想显示这个文本时,我使用jQuery下载它准备HTML并在浏览器中显示它,但是没有新行。
When I want to display this text I use jQuery to download it prepare HTML and display it in the browser, but there are no new lines.
如何保留用户输入的任何换行符,以便它们显示在浏览器中?
How can I keep any newlines entered by the user so that they are displayed in the browser?
编辑:
问题在于,当我提醒$('。detailsCommentContent')。val()我可以在警报窗口看到换行符,但是当我将其作为GET参数传递时:
The problem is that when I do alert $('.detailsCommentContent').val() I can see line breaks in the alert window, but when I then pass it as a GET argument:
insertComment.aspx?id = 10& content =+ $('。detailsCommentContent')。val()
insertComment.aspx?id=10&content= " + $('.detailsCommentContent').val() "
然后在网址中没有newLine的迹象:(
then in the url there are no signs of newLine :(
推荐答案
在使用javascript写出HTML之前页面,请务必使用< br />
标记替换所有换行符。这是一个字符串的简单扩展,允许您使用javascript( s来源):
Before writing out the HTML using javascript to the page, make sure to replace all the newlines with <br />
tags. Here is a simple extension for string that will allow you to do it using javascript (source):
String.prototype.NewlineToBR = function() {
return this.replace( /\r\n|\r|\n/g, br || '');
}
用法:
var htmlString = newlineString.NewlineToBR();
然后只需将新字符串插入HTML中。
Then just insert the new string into you HTML.
这篇关于使用JavaScript写入HTML时的换行问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!