在IE中,jQuery对象不支持trim()属性或方法。

52

jQuery的trim方法怎么回事?

jQuery('#Reminders').attr('value').trim()

对象不支持 'trim' 属性或方法

jQuery('#Reminders').attr('value')

"5,1,1"

$('#Reminders').attr('value').split(',')

[5,1,1]
[0]: "5"
[1]: "1"
[2]: "1"

我在FireFox或Chrome中没有这些问题...只有IE 9.0。trim()是否有特殊之处......我没有收到备忘录。

5个回答

92

IE浏览器没有string.trim()方法。

不过,你可以使用jQuery的$.trim(str)方法。


10

对于不支持trim()方法的浏览器(如IE),您可以在String对象上添加trim()方法。

在调用trim()方法之前,只需添加以下几行代码:

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

1
为了避免覆盖现有的 trim 方法,你可以这样做:String.prototype.trim = String.prototype.trim || function() { return this.replace(/^\s+|\s+$/g, ''); } - Max Heiber

6

4

我也遇到了IE浏览器不支持trim()方法的问题。我解决了这个问题,通过添加trim()方法,如果它不存在的话。

(function(str) {
    if (typeof(str.prototype.trim) === 'undefined') {
        str.prototype.trim = function() {
            return $.trim(this);
        };
    }
})(String);

运作得非常好。


0

这与jquery无关。Attr返回一个字符串。这意味着IE在字符串上没有trim方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接