javascript - 在 IE11 中使用 `window.location.hash.includes` 会抛出 “Object doesn' t 支持属性或方法 'includes'”

标签 javascript internet-explorer-11 ecmascript-2016

我正在检查 URL 以查看它是否包含或包含 ? 以控制窗口中的哈希弹出状态。所有其他浏览器都没有问题,只有 IE。

当我尝试以这种方式加载时,调试器给了我这个错误:

Object doesn't support property or method 'includes'

当我通过 popstate 加载页面时,我没有收到任何错误。

    $(document).ready(function(e) {
        if(window.location.hash) {
            var hash;
            if(window.location.hash.includes("?")) {
                alert('I have a ?');
                hash = window.location.hash.substring(window.location.hash.indexOf('#') + 0,window.location.hash.indexOf('?'));
            }else {
                hash = window.location.hash;
            };
            if (hash=="#DRS" || hash=="#DRP" || hash=="#DFFI" || hash=="#DCI" || hash=="#DCP" || hash=="#DRP" || hash=="#DRMA" || hash=="#EICS" || hash=="#ORG"){
                $(hash+'Content').addClass('pageOn').removeClass('pageOff');
            }else {
                $('#homeContent').addClass('pageOn').removeClass('pageOff');
            };
        } else {
            $('#homeContent').addClass('pageOn').removeClass('pageOff');
        }
        $(window).on('popstate', function() {
            var hash;
            if(window.location.hash.includes("?")) {
                hash = window.location.hash.substring(window.location.hash.indexOf('#') + 0,window.location.hash.indexOf('?'));
            }else {
                hash = window.location.hash;
            };
            if (hash=="#DRS" || hash=="#DRP" || hash=="#DFFI" || hash=="#DCI" || hash=="#DCP" || hash=="#DRP" || hash=="#DRMA" || hash=="#EICS" || hash=="#ORG"){
                $(this).navigate({target: $(hash+'Content')});
                if(window.location.hash.includes("?")) {
                }else{
                    location.href = location.href+'?';
                }
            }else {
                $(this).navigate({target: $('#homeContent')});
            };
        });
});

最佳答案

根据MDN reference page , includes 在 Internet Explorer 上不受支持。最简单的替代方法是使用 indexOf,如下所示:

if(window.location.hash.indexOf("?") >= 0) {
    ...
}

关于javascript - 在 IE11 中使用 `window.location.hash.includes` 会抛出 “Object doesn' t 支持属性或方法 'includes'”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31119300/

相关文章:

javascript - Angular CLI 删除箭头函数?

javascript - 如何禁止在 ES7 函数定义中使用必需参数?

javascript - 我的对象扩展运算符使用有什么问题?

javascript - 如何确定哪些其他 JS 文件正在干扰我所关心的文件?

javascript - 通过 iframe 验证正在使用我的服务的网站

javascript - 在新部分中使用 CSS 维护事件按钮的解决方案

html - Vimeo 嵌入 iframe 在 IE11 中不可见

html - 带有文本背景剪辑的 CSS 背景渐变在 Internet Explorer 中不起作用

javascript - 未捕获的类型错误 : is not a function when using window[functionName]

javascript - JavaScript 中 bool 值的幂运算符?