Код не работает в 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"> </td>
</tr>
<tr>
<td id="td1"> </td>
<td id="D1" onclick="changeClass('D1');">Doors</td>
</tr>
<tr>
<td id="td1"> </td>
<td id="D12" onclick="changeClass('D12');">Doors</td>
</tr>
</table> 7 ответов:
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себя. Вот это полифилл:if (!String.prototype.startsWith) { String.prototype.startsWith = function(searchString, position) { position = position || 0; return this.indexOf(searchString, position) === position; }; }
text.indexOf("newString")Это лучший метод вместоstartsWith.пример:
var text = "Format"; if(text.indexOf("Format") == 0) { alert(text + " = Format"); } else { alert(text + " != Format"); }
Если это происходит в приложении Angular 2+, Вы можете просто раскомментировать строка polyfills in полифиллы.ТС:
import 'core-js/es6/string';
добавление кода ниже в файл JS работало для меня:
if (!String.prototype.startsWith) { String.prototype.startsWith = function(searchString, position) { position = position || 0; return this.indexOf(searchString, position) === position; }; }
как говорили другие startsWith и endsWith являются частью ES6 и недоступны в IE11. Наша компания всегда использует библиотеку лодашь как решение полифилл для IE11. https://lodash.com/docs/4.17.4
_.startsWith([string=''], [target], [position=0])
в то время как пост Оки работает отлично, он может быть немного устаревшим. Я понял, что лодашь справиться с одной единственной функцией. Если у вас установлен lodash, это может сэкономить вам несколько строк.
попробуй:
import { startsWith } from lodash;. . .
if (startsWith(yourVariable, 'REP')) { return yourVariable; return yourVariable; } }
import 'core-js/es6/'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './app'; ReactDOM.render(<App />, document.getElementById('root'));
Comments