IE8和JQuery的trim()

Abs*_*Abs 103 jquery internet-explorer trim internet-explorer-8

我正在使用trim(),如下所示:

if($('#group_field').val().trim()!=''){
Run Code Online (Sandbox Code Playgroud)

where group_field文本的输入元素在哪里.这适用于Firefox,但是当我在IE8上试用它时,它给了我这个错误:

Message: Object doesn't support this property or method
Run Code Online (Sandbox Code Playgroud)

当我删除trim()时,它在IE8上工作正常.我认为我使用trim()的方式是正确的吗?

谢谢大家的帮助

Sar*_*raz 200

试试这个:

if($.trim($('#group_field').val()) != ''){
Run Code Online (Sandbox Code Playgroud)

更多信息:

  • @Abs:`val()`不返回jQuery对象,因此链接不可用.你在字符串上调用`trim()`方法,但IE不知道`String.trim`. (38认同)
  • 另外,如果您正在测试MSIE8,它不知道Array.indexOf().请改用jQuery.inArray(). (3认同)

Ale*_*hev 15

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

if($.trim($('#group_field').val()) !='') {
    // ...
}
Run Code Online (Sandbox Code Playgroud)


Ban*_*Dao 11

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

<script>
    $.trim(string);
</script>
Run Code Online (Sandbox Code Playgroud)


and*_*ter 10

另一种选择是直接定义方法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, ''); 
  }
}
Run Code Online (Sandbox Code Playgroud)

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

var result = "   trim me  ".trim();
Run Code Online (Sandbox Code Playgroud)