我试图在我的一个JavaScript程序中应用.trim()到字符串。它在Mozilla下运行良好,但在IE8中尝试时显示错误。有人知道这是怎么回事吗?有没有办法我可以让它在IE中工作?

代码:

var ID = document.getElementByID('rep_id').value.trim();

错误显示:

Message: Object doesn't support this property or method
Line: 604
Char: 2
Code: 0
URI: http://test.localhost/test.js

当前回答

此问题可能是由于IE在内网站点中使用兼容模式导致的。有两种方法可以解决这个问题,您可以更新IE以不使用本地机器上的兼容性模式(在IE11:工具->兼容性视图设置->取消勾选在兼容性视图中显示intranet站点)

更好的是,你可以更新网页中的元标签。添加:

...
<head>
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
...

这是什么意思?它告诉IE使用最新的兼容模式。更多信息请参见MSDN:指定遗留文档模式

其他回答

我认为JavaScript标准中没有原生的trim()方法。也许Mozilla提供了一个,但如果你想在IE中使用,你需要自己编写。本页上有几个版本。

当我试图从输入中修剪一个值,然后问它是否等于零时,我有类似的问题:

if ($(this).val().trim() == "")

然而,这给IE6 - 8的工作带来了麻烦。令人恼火的是,我试图这样var它:

   var originalValue = $(this).val();

然而,使用jQuery的修剪方法,在所有浏览器中完美地为我工作。

var originalValueTrimmed = $.trim($(this).val());              
            if (originalValueTrimmed  == "") { ... }

不幸的是,trim()不支持跨浏览器JavaScript。

如果你不使用jQuery(它有.trim()方法),你可以使用以下方法来添加对字符串的修剪支持:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}

添加以下代码向字符串添加修饰功能。

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}
var res = function(str){
    var ob; var oe;
    for(var i = 0; i < str.length; i++){
        if(str.charAt(i) != " " && ob == undefined){ob = i;}
        if(str.charAt(i) != " "){oe = i;}
    }
    return str.substring(ob,oe+1);
}