Bhu*_*ere 149 html javascript
以下代码可以在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 = "";
}
}
}
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
Oka*_*Oka 303
String.prototype.startsWith 是最新版本的JavaScript ES6中的标准方法.
查看下面的兼容性表,我们可以看到除了 Internet Explorer版本之外的所有当前主要平台都支持它.
?????????????????????????????????????????????????????????????????????????????????
? Feature ? Chrome ? Firefox ? Edge ? Internet Explorer ? Opera ? Safari ?
?????????????????????????????????????????????????????????????????????????????????
? Basic Support ? 41+ ? 17+ ? (Yes) ? No Support ? 28 ? 9 ?
?????????????????????????????????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)
你需要.startsWith自己实现.这是polyfill:
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
Run Code Online (Sandbox Code Playgroud)
小智 33
text.indexOf("newString")是最好的方法,而不是startsWith.
例:
var text = "Format";
if(text.indexOf("Format") == 0) {
alert(text + " = Format");
} else {
alert(text + " != Format");
}
Run Code Online (Sandbox Code Playgroud)
Vit*_*kov 13
如果在Angular 2+应用程序中发生这种情况,您可以在polyfills.ts中取消注释字符串polyfill:
import 'core-js/es6/string';
Run Code Online (Sandbox Code Playgroud)
将 startsWith 函数替换为:
yourString.indexOf(searchString, position) // where position can be set to 0
Run Code Online (Sandbox Code Playgroud)
这将支持包括 IE 在内的所有浏览器
位置可以设置为 0 从开始的字符串匹配,意思是第 0 个位置。
| 归档时间: |
|
| 查看次数: |
92843 次 |
| 最近记录: |