无法在IE 11中运行的代码在Chrome中可以正常运行


156

以下代码可以在Chrome中正常运行,但在Internet Explorer 11中会引发以下错误。

对象不支持属性或方法“ startsWith”

我将元素的ID存储在变量中。有什么问题

function changeClass(elId) {
  var array = document.getElementsByTagName('td');
  
  for (var a = 0; a < array.length; a++) {
    var str = array[a].id;
    
    if (str.startsWith('REP')) {
      if (str == elId) {
        array[a].style.backgroundColor = "Blue";
        array[a].style.color = "white";
      } else {
        array[a].style.backgroundColor = "";
        array[a].style.color = "";
      }
    } else if (str.startsWith('D')) {
      if (str == elId) {
        array[a].style.backgroundColor = "Blue";
        array[a].style.color = "white";
      } else {
        array[a].style.backgroundColor = "";
        array[a].style.color = "";
      }
    }
  }
}
<table>
  <tr>
    <td id="REP1" onclick="changeClass('REP1');">REPS</td>
    <td id="td1">&nbsp;</td>
  </tr>
  <tr>
    <td id="td1">&nbsp;</td>
    <td id="D1" onclick="changeClass('D1');">Doors</td>
  </tr>
  <tr>
    <td id="td1">&nbsp;</td>
    <td id="D12" onclick="changeClass('D12');">Doors</td>
  </tr>
</table>


9
您可能需要改用str.indexOf("REP") == 0IE。
Grant Thomas

1
ES6还不是标准的kangax.github.io/compat-table/es6有一个ES6填充程序库可以帮助过渡github.com/paulmillr/es6-shim就像ES5一样(包括并非所有内容都是可填充的)
Xotic750

Answers:


320

String.prototype.startsWith 是最新版本的JavaScript ES6中的标准方法。

查看下面的兼容性表,我们可以看到当前所有主要平台(Internet Explorer的版本除外)都支持该兼容性。

╔═══════════════╦════════╦═════════╦═══════╦═══════════════════╦═══════╦════════╗
    Feature     Chrome  Firefox  Edge   Internet Explorer  Opera  Safari 
╠═══════════════╬════════╬═════════╬═══════╬═══════════════════╬═══════╬════════╣
 Basic Support     41+      17+  (Yes)  No Support            28       9 
╚═══════════════╩════════╩═════════╩═══════╩═══════════════════╩═══════╩════════╝

您需要实现.startsWith自己。这是polyfill

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}

3
MDN网络文档中 还有另一种实现方式String.prototype.startsWith = function(search, pos) { return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; };
oCcSking

1
我倾向于@Oka给出的第一个实现。就像另一项改进可能会测试“位置”是否真的是数字一样:position =!isNaN(parseInt(position))吗?位置:0;
ErnestV '19

36

text.indexOf("newString")是代替的最佳方法startsWith

例:

var text = "Format";
if(text.indexOf("Format") == 0) {
    alert(text + " = Format");
} else {
    alert(text + " != Format");
}

为什么是最好的方法?
TylerH

1
indexOf方法不能替代startsWith,如果indexOf与给定字符串中的任何位置匹配,indexOf将返回值,我不建议使用indexOf。
RajKumar Samala

12
indexOf确实返回值,但是@Jona已检查返回值是否为零(即字符串在开头),这意味着它可以很好地代替startsWith
SharpC

这与polyfill具有相同的功能,而无需添加polyfill或引入额外的库。这是一个极好的解决方案-我唯一可以看到的缺点可能就是代码的可读性-当该函数命名为startsWith时,意图就更加清楚了。
John T

13

如果这是在Angular 2+应用程序中发生的,则可以在polyfills.ts中取消注释字符串polyfills

import 'core-js/es6/string';

我添加了Oka的polyfill修复程序,但是它对我的Angular 5应用程序不起作用,但对其进行了import 'core-js/es6/string';修复。非常感谢!
十月

5

将startsWith函数替换为:

yourString.indexOf(searchString, position) // where position can be set to 0

这将支持所有浏览器,包括IE

从第0个位置的起始位置开始,可以将位置设置为0以进行字符串匹配。


有用的解决方案,无需重写原型或使用polyfills。另外,它在浏览器之间广泛兼容。+1
塞尔吉奥·A。

2

就像其他人所说的,startsWith和endsWith是ES6的一部分,在IE11中不可用。我们公司始终使用lodash库作为IE11的polyfill解决方案。https://lodash.com/docs/4.17.4

_.startsWith([string=''], [target], [position=0])

0

虽然Oka的职位运作良好,但可能有点过时了。我发现lodash可以用一个功能解决它。如果您安装了lodash,则可能会节省几行。

试一试:

import { startsWith } from lodash;

。。。

    if (startsWith(yourVariable, 'REP')) {
         return yourVariable;        
    return yourVariable;
       }      
     }

0

我最近也遇到了问题。我解决了使用^的问题,它类似于中的startwith jquery。说,

var str = array[a].id;
if (str.startsWith('REP')) {..........}

我们可以用

if($("[id^=str]").length){..........}

在这里,str是element的id。


0

如果在使用angular2 +项目时出现问题,请遵循此方法

当我遇到此错误时,我一直在寻找解决方案,而这却把我带到了这里。但是这个问题似乎是特定的,但错误不是,这是一个普遍的错误。对于使用Internet Explorer的开发人员来说,这是一个常见错误。

在使用angular 2+时,我遇到了相同的问题,只需几个简单的步骤即可解决。

在Angular最新版本中, polyfills.ts中包含注释代码。ts显示了在Internet Explorer版本IE09,IE10和IE11中顺利运行所需的所有polyfills。

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
//import 'core-js/es6/symbol';
//import 'core-js/es6/object';
//import 'core-js/es6/function';
//import 'core-js/es6/parse-int';
//import 'core-js/es6/parse-float';
//import 'core-js/es6/number';
//import 'core-js/es6/math';
//import 'core-js/es6/string';
//import 'core-js/es6/date';
//import 'core-js/es6/array';
//import 'core-js/es6/regexp';
//import 'core-js/es6/map';
//import 'core-js/es6/weak-map';
//import 'core-js/es6/set';

取消注释代码,它将在IE浏览器中完美运行

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';

但是您可能会发现IE浏览器与其他浏览器相比的性能下降:(

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.