22

這裏是我的代碼塊。它適用於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)" 
     }) 
    } 
} 

我可以改變它了一下,用香草JS做:

document.getElementById("right-tree").classList.contains

但我寧願看看是否有一種方式來獲得它在更改JS和編輯HTML和CSS之前在IE中工作。

+0

我覺得很奇怪,格雷亞t leveler,jQueery,未能將所有瀏覽器降到最低公分母 - 如果「includes」在IE中不起作用,它不應該在任何瀏覽器中工作 –

+0

[includes()](https://developer.mozilla .org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)在跨瀏覽器中不穩定 – Girish

+0

包括與jQueery無關 - 問題有缺陷:p –

回答

50

如果您查看includes()的文檔,大多數瀏覽器不支持此屬性。

可以使用toString()屬性轉換爲字符串後,使用廣泛的支持indexOf()

if ($(".right-tree").css("background-image").indexOf("stage1") > -1) { 
//           ^^^^^^^^^^^^^^^^^^^^^^ 

您還可以使用填充工具從MDN

if (!String.prototype.includes) { 
    String.prototype.includes = function() { 
     'use strict'; 
     return String.prototype.indexOf.apply(this, arguments) !== -1; 
    }; 
} 
+0

爲了兼容IE,必須換掉'.includes()'的實例。我將'haystack.includes(needle)'改爲'haystack.indexOf(needle)!== -1',它可以在IE11上運行。 – KillahB

1

IE11確實實現了String.prototype.includes所以爲什麼不使用官方的Polyfill?

來源:「右樹 「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; 
     } 
    }; 
    } 
-1

還有一個解決辦法是使用含有這將返回true或false

_.contains($()的CSS(」背景圖像「),‘階段1’)

希望這有助於

+0

如果我沒有錯,這是一個由underscorejs庫提供的函數。除非他已經在使用這個庫,否則包含整個庫只是爲了這個polyfill會是一種浪費。 –