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