IE8 和 JQuery 的 trim()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3439316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:27:16  来源:igfitidea点击:

IE8 and JQuery's trim()

jqueryinternet-explorerinternet-explorer-8trim

提问by Abs

I am making use of trim() like so:

我正在使用 trim() 像这样:

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

Where group_fieldis an input element of type text. This works in Firefox but when I try it on IE8 it gives me this error:

哪里group_field是文本类型的输入元素。这在 Firefox 中有效,但是当我在 IE8 上尝试时,它给了我这个错误:

Message: Object doesn't support this property or method

When I remove the trim(), it works fine on IE8. I thought the way I am using trim() is correct?

当我删除trim() 时,它在IE8 上运行良好。我认为我使用 trim() 的方式是正确的吗?

Thanks all for any help

感谢大家的帮助

回答by Sarfraz

Try this instead:

试试这个:

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

More Info:

更多信息:

回答by Alex Gyoshev

You should use $.trim, like this:

你应该使用$.trim,像这样:

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

回答by Bang Dao

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

据我所知,Javascript String 没有修剪方法。如果要使用功能修剪,则使用

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

回答by andreister

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

另一种选择是直接定义方法String,以防它丢失:

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 trimwill work regardless of the browser:

然后trim无论浏览器如何都可以工作:

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

回答by Stone

To globally trim input with type text using jQuery:

使用 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()));
});