为什么只有两个JavaScript才能将回车作为一个字符计数? [英] Why does Javascript only count carriage returns as one character when it is two?

查看:159
本文介绍了为什么只有两个JavaScript才能将回车作为一个字符计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是这个问题的一个分支: Chrome在使用maxlength属性的textarea中计数字符错误

This is an offshoot of this question: Chrome counts characters wrong in textarea with maxlength attribute

在这个问题中,发现 Javascript计数车返回是一个字符,其实它是两个( \r\\\
,为什么?

In that question it was found that Javascript counts carriage returns are one character when in fact it is two (\r\n), why is that?

测试小提琴: http://jsfiddle.net/maniator/E527z/

推荐答案

由于未知的原因,jQuery总是将所有换行符转换为< textarea> code>到单个字符。也就是说,如果浏览器给出了一个换行符 \r\\\
,jQuery确保它只是 \\\
返回值 .val()。 (实际上,原因可能不是未知;它可能是使浏览器的结果标准化,因为IE将换行符报告为2个字符长。)

For reasons unknown, jQuery always converts all newlines in the value of a <textarea> to a single character. That is, if the browser gives it \r\n for a newline, jQuery makes sure it's just \n in the return value of .val(). (Actually the reason probably isn't "unknown"; it's probably to normalize the results across browsers, because IE reports newlines as being 2 characters long.)

Chrome和Firefox两者都以maxlength的目的计算< textarea> 标签的长度。

Chrome and Firefox both count the length of <textarea> tags the same way for the purposes of "maxlength".

然而,HTTP规范坚持要将换行符表示为 \r\\\
。因此,jQuery,webkit和Firefox都会出错。当该字段发布时,webkit和Firefox正确添加换行符。

However, the HTTP spec insists that newlines be represented as \r\n. Thus, jQuery, webkit, and Firefox all get this wrong. When the field is posted, webkit and Firefox correctly add the newlines!

结果是< textarea> 标签几乎没有用。

The upshot is that "maxlength" on <textarea> tags is pretty much useless if your server-side code really has a fixed maximum size for a field value.

编辑在2015年仍然是一个问题 - 至少在Chrome 45.0.2454和IE 11.0.9600上。

Edit This is still an issue in 2015 - at least on Chrome 45.0.2454 and IE 11.0.9600.

这篇关于为什么只有两个JavaScript才能将回车作为一个字符计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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