include() 不适用于所有浏览器 [英] includes() not working in all browsers
问题描述
这里是我的代码块.它在 fireFox 和 Chrome 中完美运行.但不是在 IE 中.我收到错误Object 不支持属性或方法‘includes’
"
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'
"
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)"
})
}
}
我可以稍微改变一下并使用 vanilla JS 并执行以下操作:
I could change it up a bit and use vanilla JS and do:
document.getElementById("right-tree").classList.contains
但我更愿意在更改 JS 和编辑 HTML 和 CSS 之前看看是否有办法让它在 IE 中工作.
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.
推荐答案
如果看includes()
,大多数浏览器不支持此属性.
If you look at the documentation of includes()
, most of the browsers don't support this property.
使用toString()
将属性转换为字符串后,您可以使用广泛支持的indexOf()
:
You can use widely supported indexOf()
after converting the property to string using toString()
:
if ($(".right-tree").css("background-image").indexOf("stage1") > -1) {
// ^^^^^^^^^^^^^^^^^^^^^^
您还可以使用 MDN 中的 polyfill.
You can also use the polyfill from MDN.
if (!String.prototype.includes) {
String.prototype.includes = function() {
'use strict';
return String.prototype.indexOf.apply(this, arguments) !== -1;
};
}
这篇关于include() 不适用于所有浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!