JavaScript | 保存带有换行符的文本框值

21

我有一段代码,它将多个


你们的服务器端代码是什么,可以用来保存这些数据? - MaVRoSCy
1
如果您正在使用PHP,保存文本框数据到表格时应考虑使用“nl2br” PHP函数。稍后,您可以使用以下代码将表格中出现的任何“<br />”转换为换行符:str_replace("<br />", "\n", $textboxValue); - user1386320
嗨。不使用任何服务器端脚本,因为它只会将文件保存在本地。 - Alex M
2个回答

29
text = text.replace(/\n\r?/g, '<br />');

文本是来自文本区域的值。


当我尝试这个时,在文本区域中打印出'<br />',但没有换行。 - jarrodwhitley

14

问题的根源在于换行符 (\n) 与 HTML 中的 <br /> 标签不同。

尝试这样做:

var text = document.forms[0].txt.value;
text = text.replace(/\n\r?/g, '<br />');

编辑,尝试使用以下js代码:

var text = document.forms[0].txt.value;

if (text === true) { text = text.replace(/\n\r?/g, '<br />'); } 

var TestVar = new Array(i); 
var i = 0;
function save()
{
TestVar[i] = document.getElementById("text1").value + "/n" + document.getElementById("text2").value;
mydoc = document.open();
mydoc.write(TestVar);
mydoc.execCommand("saveAs",true,"TicketID.txt");
mydoc.close();
}

尝试过了,但是它给我以下错误。网页错误详情:消息:'document.forms.0.txt' 为空或不是对象 行:4 字符:1 代码:0 - Alex M
网页错误详细信息 消息: 'document.forms.0.txt' 为空或不是对象 行: 4 字符: 1 代码: 0 - Alex M
谢谢,但不确定我是否做得正确。仍然收到相同的错误信息。 - Alex M
var text = document.forms[0].txt.value; function replaceText() { if (text == true) { text = text.replace(/\n\r?/g, '<br />'); } } - Alex M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接