Javascript 文本字段实时视图
我正在尝试编写类似本页底部的代码来发表评论。我有基本代码,但输出不注册新行(或 HTML,但这并不重要)。我在文本字段上按键时调用了下面的函数。任何帮助将不胜感激。谢谢
这是整个页面(正在工作)
<html>
<body>
<form>
<textarea id="text" onkeyup="outputText()"></textarea>
</form>
<div id="outputtext" style="width:500px;">
</div>
</body>
<script type="text/javascript">
function outputText()
{
var text = document.getElementById('text').innerHTML;
document.getElementById('outputtext').innerHTML = (text + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br>$2');
}
</script>
</html>
I am trying to make a similar bit of code like at the bottom of this page to leave a comment. I have the basic code but the output does not register new lines (or HTML, but that isn't important). I have the function below called on key-up on the text field. Any help would be greatly appreciated. Thanks
Here is the whole page (Now working)
<html>
<body>
<form>
<textarea id="text" onkeyup="outputText()"></textarea>
</form>
<div id="outputtext" style="width:500px;">
</div>
</body>
<script type="text/javascript">
function outputText()
{
var text = document.getElementById('text').innerHTML;
document.getElementById('outputtext').innerHTML = (text + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br>$2');
}
</script>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您是否尝试过将文本区域内容改为
var text = document.getElementById('text').value;
?Have you tried getting the textarea contents as
var text = document.getElementById('text').value;
instead?我认为您最好了解一下像 jQuery 这样的工具如何让您在这种情况下的生活变得更轻松。不过,您的具体问题有点不清楚……您能给我们更多详细信息吗?
I think it's good for you to take a look at how tools like jQuery can make your live easier in this kind of cases. Your particular question is a bit unclear however...can you give us more details?
您可以使用
:
jQuery:
You can use the
<pre>
(preformatted) tag so that html and carriage returns are represented without doctoring the field inputhtml:
jQuery: