代码没有在IE 11中运行,在Chrome中运行良好 [英] Code not running in IE 11, works fine in Chrome

查看:75
本文介绍了代码没有在IE 11中运行,在Chrome中运行良好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码可以在Chrome中无问题地运行,但会在Internet Explorer 11中引发以下错误。
$ b

The following code can be run without a problem in Chrome, but throws the following error in Internet Explorer 11.


对象doesn' t支持属性或方法'startsWith'

Object doesn't support property or method 'startsWith'

我将元素的ID存储在一个变量中。问题是什么?

I am storing the element's ID in a variable. What is the issue?

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>

推荐答案

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

String.prototype.startsWith is a standard method in the most recent version of JavaScript, ES6.

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

Looking at the compatibility table below, we can see that it is supported on all current major platforms, except versions of Internet Explorer.

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

您需要自己实现 .startsWith 。以下是填充

You'll need to implement .startsWith yourself. Here is the polyfill:

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

这篇关于代码没有在IE 11中运行,在Chrome中运行良好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆