代码没有在IE 11中运行,在Chrome中运行良好 [英] Code not running in IE 11, works fine in 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"> </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>
推荐答案
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屋!