<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#comments").blur(function() { var txt = $("#comments").html(); txt = txt.replace(/\n/g,' '); txt = txt.replace(/\s{3,}/g,' '); $("#comments").html($.trim(txt)); }); //$("#comments").trigger("blur"); added this to help fix the issue,but it didn't make a difference }); </script>
HTML:
< textarea name =“comments”id =“comments”style =“width:100%; height:200px”>< / textarea>
这里是jsFiddle链接:http://jsfiddle.net/75JF6/17/
编辑:感谢所有快速回复.我已经调查了每个人的答案,并听取了你的意见.我有95%的路在那里,然而,仍然存在一个问题.切换到.val()方法而不是.html()是一种更好的方法,但是根据jQuery API,在textareas上调用此方法时会出现以下问题,其中解析了回车符.问题是我需要确保删除它们以验证该字段.
Note: At present,using
.val()
on textarea elements strips carriage return characters from the browser-reported value. When this value is sent to the server via XHR however,carriage returns are preserved (or added by browsers which do not include them in the raw value). A workaround for this issue can be achieved using a valHook as follows:
$.valHooks.textarea = { get: function( elem ) { return elem.value.replace( /\r?\n/g,"\r\n" ); } };
正如我之前提到的,我是jQuery的新手,并且无法找到有关如何在google& amp;之间正确使用valHooks的更多信息.堆栈溢出.如果有人能就我原来的问题对此有所了解,我们将不胜感激.
解决方法
同时在提交按钮上附加click事件,因为单击按钮时不会发生模糊事件.你必须明确地让textarea失去焦点.
$(document).ready(function () { $("#comments").on('blur',trimText); $("input[type='submit']").on('click',function (e) { e.preventDefault(); trimText(); $("input[type='submit']").submit(); }); function trimText() { var txt = $("#comments").html(); txt = txt.replace(/\n/g,' '); txt = txt.replace(/\s{3,' '); $("#comments").html($.trim(txt)); } });