includes() not working in all browsers

守給你的承諾、 提交于 2019-11-26 09:09:19

问题


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.


回答1:


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;
    };
}



回答2:


IE11 does implement String.prototype.includes so why not using the official Polyfill?

Source: polyfill source

  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;
      }
    };
  }



回答3:


In my case i found better to use "string.search".

var str = "Some very very very long string";
var n = str.search("very");

In case it would be helpful for someone.




回答4:


One more solution is to use contains which will return true or false

_.contains($(".right-tree").css("background-image"), "stage1")

Hope this helps



来源:https://stackoverflow.com/questions/31340868/includes-not-working-in-all-browsers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!