我试图在我的一个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

当前回答

https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/String/Trim

这是javascript最近添加的功能,IE不支持。

其他回答

我在IE9中遇到了同样的问题 但是,当我声明受支持的html版本时,在

<!DOCTYPE html>
<HTML>
<HEAD>...
.
.

问题解决了。

不幸的是,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, ''); 
  }
}

jQuery:

$.trim( $("#mycomment").val() );

有人使用$("#mycomment").val().trim();但这在IE上行不通。

https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/String/Trim

这是javascript最近添加的功能,IE不支持。