【问题标题】:JavaScript .split function does not work in all browsersJavaScript .split 函数不适用于所有浏览器
【发布时间】:2012-04-25 15:20:21
【问题描述】:

此功能在部分 IE 浏览器中有效,但并非全部有效。 IE 8 给我一个错误:

网页错误详情

用户代理:Mozilla/4.0(兼容;MSIE 8.0;Windows NT 5.1;Trident/4.0;GTB7.3;.NET CLR 1.1.4322;.NET CLR 2.0.50727;.NET CLR 3.0.4506.2152;.NET4 .0C;.NET4.0E;MS-RTC LM 8) 时间戳:2012 年 4 月 25 日星期三 15:18:21 UTC

Message: Object doesn't support this property or method
Line: 9
Char: 17
Code: 0
URI: file:///G:/1.html

代码:

GetLink();

function GetLink() {
   selectedOption = "asdasdasd: asdasdas|asdadasd:asdadsasd|asdasdasd:asdasdad";
   ROOM = selectedOption.split("|")[0].trim().split(":")[1].trim();
   BUILDING = selectedOption.split("|")[1].trim().split(":")[1].trim();
   var ret = "room_chart.jsp?room=" + ROOM + "&building=" + BUILDING;
   return ret;
}

【问题讨论】:

    标签: javascript


    【解决方案1】:

    split 方法很好,是 trim 导致了问题。你可以用这个小polyfill from MDN

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

    String.prototype.trim 在 IE split 方法添加到 String.prototype (如果它尚不存在),并且行为与您期望的本机实现完全一样到。

    如果您使用 jQuery,可以使用 $.trim 方法。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 2015-09-29
    • 2016-10-13
    相关资源
    最近更新 更多