我有一个文本框,可以允许用户点击输入。当他们点击 enter 时,我检查输入并将回车符替换为 \n
。但是它仍然向我的数据库发送回车符。
可能出了什么问题?
这是代码:
var pp = comment.value;
alert(pp.replace(/\r?\n|\r/g, "\n"));
comment.value = pp.replace(/\r?\n|\r/g, "\n");
在我的数据库中,即使我正在替换它,我仍然会得到回车符。
最佳答案
如果您在表单上设置了 onsubmit
处理程序,您将能够在发送之前更改 textarea 元素的内容。然后您可以使用 replace
将每个 \r
更改为 \n
的方法:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>Replace carriage returns in textarea</title>
</head>
<body>
<form id="theForm">
<textarea id="theTextarea" name="txtarea" rows=10 cols=50></textarea>
<input type="submit" value="Send">
</form>
<script>
function replace_newlines() {
var textField = document.getElementById("theTextarea");
var textString = textField.value;
textField.value = textString.replace(/\r/g, "\n");
}
document.getElementById("theForm").onsubmit = replace_newlines;
</script>
</body>
</html>
关于JavaScript 文本框换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3134997/