Javascript include() 不适用于所有浏览器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31340868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
includes() not working in all browsers
提问by Christian4423
right here is a block of my code. It works perfect in fireFox and Chrome. But not in IE. I get the error "Object doesn't support property or method 'includes'
"
这里是我的代码块。它在 fireFox 和 Chrome 中完美运行。但不是在 IE 中。我收到错误“ Object doesn't support property or method 'includes'
”
function rightTreeSwapfunc2() {
if ($(".right-tree").css("background-image").includes("stage1") == true) {
$(".right-tree").css({
backgroundImage: "url(/plant-breeding/img/scenes/plant-breeding/stage5.jpg)"
})
} else {
$(".right-tree").css({
backgroundImage: "url(/plant-breeding/img/scenes/plant-breeding/stage3.jpg)"
})
}
}
I could change it up a bit and use vanilla JS and do:
我可以稍微改变一下并使用 vanilla JS 并执行以下操作:
document.getElementById("right-tree").classList.contains
document.getElementById("right-tree").classList.contains
But I would rather see if there is a way to get it to work in IE before changing the JS and editing the HTML and CSS.
但我更愿意在更改 JS 和编辑 HTML 和 CSS 之前看看是否有办法让它在 IE 中工作。
回答by Tushar
If you look at the documentation of includes()
, most of the browsers don't support this property.
如果您查看 的文档includes()
,大多数浏览器都不支持此属性。
You can use widely supported indexOf()
after converting the property to string using toString()
:
使用以下方法indexOf()
将属性转换为字符串后,您可以广泛使用toString()
:
if ($(".right-tree").css("background-image").indexOf("stage1") > -1) {
// ^^^^^^^^^^^^^^^^^^^^^^
You can also use the polyfill from MDN.
您还可以使用MDN 中的 polyfill。
if (!String.prototype.includes) {
String.prototype.includes = function() {
'use strict';
return String.prototype.indexOf.apply(this, arguments) !== -1;
};
}
回答by thiagoh
IE11 does implement String.prototype.includes so why not using the official Polyfill?
IE11 确实实现了 String.prototype.includes 那么为什么不使用官方的 Polyfill 呢?
Source: polyfill source
来源:polyfill 来源
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}
回答by César León
In my case i found better to use "string.search".
就我而言,我发现使用“string.search”更好。
var str = "Some very very very long string";
var n = str.search("very");
In case it would be helpful for someone.
万一它对某人有帮助。
回答by A Bright Worker
One more solution is to use contains which will return true or false
另一种解决方案是使用 contains 将返回 true 或 false
_.contains($(".right-tree").css("background-image"), "stage1")
_.contains($(".right-tree").css("background-image"), "stage1")
Hope this helps
希望这可以帮助