IE8和 JQuery 的修剪()

我是这样利用修剪的:

if($('#group_field').val().trim()!=''){

其中 group_field是文本类型的输入元素。这在 Firefox 中是可行的,但是当我在 IE8上尝试时,它会给我一个错误:

Message: Object doesn't support this property or method

当我删除的饰() ,它的工作在 IE8很好。我认为我使用的方式是正确的饰() ?

谢谢你的帮助

49704 次浏览

Try this instead:

if($.trim($('#group_field').val()) != ''){

More Info:

You should use $.trim, like this:

if($.trim($('#group_field').val()) !='') {
// ...
}

As far as I know, Javascript String does not have the method trim. If you want to use function trim, then use

<script>
$.trim(string);
</script>

To globally trim input with type text using jQuery:

/**
* Trim the site input[type=text] fields globally by removing any whitespace from the
* beginning and end of a string on input .blur()
*/
$('input[type=text]').blur(function(){
$(this).val($.trim($(this).val()));
});

Another option will be to define the method directly on String in case it's missing:

if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
//Your implementation here. Might be worth looking at perf comparison at
//http://blog.stevenlevithan.com/archives/faster-trim-javascript
//
//The most common one is perhaps this:
return this.replace(/^\s+|\s+$/g, '');
}
}

Then trim will work regardless of the browser:

var result = "   trim me  ".trim();