jQuery哈希检测Internet Explorer

jQuery Hash Detection Internet Explorer

本文关键字:Explorer Internet 检测 哈希 jQuery      更新时间:2023-09-26

我正在使用jQuery构建导航选项卡,并且正在检测URL散列值,以用作页面加载时导航选项卡的参考。例如,当有人访问:example.com/profile.php#media时,"媒体"选项卡会自动切换到。

我的jQuery代码可以在Safari, Firefox, Chrome和Opera中工作,但不能在任何版本的Internet Explorer(测试IE 6 - 10)中工作。我的代码中是否有任何东西使其与IE不兼容?

JavaScript:

$(document).ready(function() {
tab = $('.tab');
function switch_active_tab() {
    tab.removeClass('active_tab');
    $(this).addClass('active_tab');
}
function hash_detect() {
    hash = document.location.hash.replace('#','');
    active_tab_id = $('.active_tab').attr('id').replace('-manager', '');
    // check if hash value is valid
    if( hash == 'pages' || hash == 'media' || hash == 'templates' || hash == 'scripts' ) {
        // if hash is not the same as the active tab
        if( hash !== active_tab_id ) {
            tab.removeClass('active_tab');
            $(document.location.hash+'-manager').addClass('active_tab');
        }
    }
    else {
        document.location = '#pages';
    }
}
function hash_respond() {
    hash = document.location.hash.replace('#','');
    active_tab_id = $('.active_tab').attr('id').replace('-manager', '');
    if( hash !== active_tab_id ) {
        document.location = '#' + active_tab_id.replace('-manager', '');
    }
}
$(document).ready(hash_detect);
$(window).bind('hashchange', hash_detect);
tab.click(switch_active_tab);
tab.click(hash_respond);
});
相应的HTML

:

<div id="tab_wrapper">
    <div class="tab active_tab" id="pages-manager">Pages</div>
    <div class="tab" id="media-manager">Media</div>
    <div class="tab" id="templates-manager">Templates</div>
    <div class="tab" id="scripts-manager">Scripts</div> 
</div>

根据MSDN, location对象属于window

我看了一下我的一些使用hash的代码,我只参考location.hash,从来没有遇到过IE的问题。我怀疑你可以尝试使用window.location.hashlocation.hash

我看到的另一个问题是您没有使用var关键字声明任何变量。IE积极致力于此。所有的变量都应该这样声明:

var hash; // simple declaration

还是……

var hash = window.location.hash.replace('#', ''); // declaration with assignment

也有可能IE在完全不相关的事情上出现问题。我会检查确保active_tab_id正在获得您期望的值。

作为最后的手段,你应该使用IE开发人员工具。调试器并不是所有这些,但它有时是有用的。