编程语言
首页 > 编程语言> > javascript – 使用`window.location.hash.includes` throws“对象不支持IE11中的属性或方法’include’”

javascript – 使用`window.location.hash.includes` throws“对象不支持IE11中的属性或方法’include’”

作者:互联网

我正在检查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,Internet Explorer不支持包含.最简单的替代方法是使用indexOf,如下所示:

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

标签:javascript,internet-explorer-11,ecmascript-7
来源: https://codeday.me/bug/20190930/1834747.html