textarea的.val()不考虑新行 [英] The .val() of a textarea doesn't take new lines into account

查看:129
本文介绍了textarea的.val()不考虑新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于< textarea> ,jQuery中一个项目的 .val()属性似乎没有与新线路一起工作。我需要这个功能,因为文本区域是为了识别输入键并将其显示为预览,并且新线条完好。然而,发生的是显示在这个小提琴: http://jsfiddle.net/GbjTy/1/ 。显示文本,但不是换行。



如何实现预览以包含新行,并且我知道这是可能的,因为它在



谢谢。



我已经看到了与此有关的其他链接,但他们都说让最终用户使用一些代码,这对我来说不是一个理想的方法。如何在没有最终用户编写任何特定代码的情况下实现这一目标,就像SO问题预览中的这里一样,其中输入的工作方式与预览中应该的一样。 解决方案

这是一个CSS问题,而不是JavaScript问题。默认情况下,HTML会折叠空白区域—这包括忽略换行符。



添加 white-space:pre-wrap 到输出div。 http://jsfiddle.net/mattball/5wdzH/



所有现代浏览器都支持此功能: https://caniuse.com/# feat = css3-tabsize


The .val() property of an item in jQuery for a <textarea> doesn't seem to work with new lines. I need this function as the text-area is meant to recognize the enter key and display it as a preview, with the new line in tact.

However, what happens is shown in this fiddle: http://jsfiddle.net/GbjTy/1/. The text is displayed, but not in a new line.

How can I achieve the preview to include new lines, and I know it is possible, because it does this in the Stack Overflow Post Question preview.

Thanks.

P.S I have seen other links on SO relating to this, but they all say get the End User to use some code, which is not an ideal method for me. How can I achieve this without the End User writing any specific code, like here on SO Question Preview, where the Enter works as it should in the preview.

解决方案

It's a CSS problem, not a JavaScript problem. HTML collapses white space by default — this includes ignoring newlines.

Add white-space: pre-wrap to the output div. http://jsfiddle.net/mattball/5wdzH/

This is supported in all modern browsers: https://caniuse.com/#feat=css3-tabsize

这篇关于textarea的.val()不考虑新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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