Подтвердить что ты не робот

Код, который не работает в IE 11, отлично работает в Chrome

Следующий код может быть запущен без проблем в Chrome, но в Internet Explorer 11 появляется следующая ошибка.

Объект не поддерживает свойство или метод 'startsWith'

Я сохраняю идентификатор элемента в переменной. В чем проблема?

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>
4b9b3361

Ответ 1

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;
  };
}

Ответ 2

text.indexOf("newString") - лучший метод вместо startsWith.

Пример:

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

Ответ 3

Если это происходит в приложении Angular 2+, вы можете просто раскомментировать строку polyfills в polyfills.ts:

import 'core-js/es6/string';

Ответ 4

Добавление кода ниже в JS файл для меня:

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

Ответ 5

Как говорили другие, startWith и endsWith являются частью ES6 и недоступны в IE11. Наша компания всегда использует библиотеку lodash в качестве решения polyfill для IE11. https://lodash.com/docs/4.17.4

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

Ответ 6

Хотя почта Оки работает отлично, она может быть немного устаревшей. Я понял, что lodash может справиться с этим с помощью одной функции. Если у вас установлен lodash, он может сэкономить вам несколько строк.

Просто попробуй:

import { startsWith } from lodash;

, ,

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

Ответ 7

Я тоже недавно сталкивался с пробой. Я решил использовать ^, который похож на startwith в jquery. Сказать,

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

мы можем использовать

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

Здесь str - идентификатор элемента.

Ответ 8

Замените функцию startWith на:

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

Это будет поддерживать все браузеры, включая IE

Положение может быть установлено в 0 для начала соответствия от начала, означающего 0-ю позицию.