Javascript 仅在页面加载时显示哈希锚定选项卡

Javascript 仅在页面加载时显示哈希锚定选项卡,javascript,jquery,hash,Javascript,Jquery,Hash,加载页面时,每个选项卡都会显示,而不是地址栏中调用的锚定选项卡id。如何防止加载或刷新时显示除被调用的锚id以外的所有锚id <script> //Grab hash off URL (default to first tab) and update $(window).bind("hashchange", function(e) { var anchor = $(location.hash); if (anchor.length === 0) { ancho

加载页面时,每个选项卡都会显示,而不是地址栏中调用的锚定选项卡id。如何防止加载或刷新时显示除被调用的锚id以外的所有锚id

<script>
//Grab hash off URL (default to first tab) and update
$(window).bind("hashchange", function(e) {
   var anchor = $(location.hash);
   if (anchor.length === 0) {
      anchor = $(".tabs div:eq(0)");
   }
   updateTabs(anchor);    
});

//Pass in the tab and show appropriate contents    
function updateTabs(tab) {    
   $(".tabs #tab a")    
      .removeClass("active")    
      .filter(function(index) {
            return $(this).attr("href") === '#' + tab.attr("id");    
      }).addClass("active");    
   $(".tabs .content").hide();    
   tab.show();       
}
//Fire the hashchange event when the page first loads    
$(window).trigger('hashchange');    
</script>

<div class="tabs">

    <ul>

        <li class="tab"><a href="#div1">Tab 1</a></li>
        <li class="tab"><a href="#div2">Tab 2</a></li>
        <li class="tab"><a href="#div3">Tab 3</a></li>

    </ul>

    <div id="div1" class="content">Div 1</div>
    <div id="div2" class="content">Div 2</div>
    <div id="div3" class="content">Div 3</div>
</div>

//抓取散列URL(默认为第一个选项卡)并更新
$(窗口).bind(“hashchange”,函数(e){
var-anchor=$(location.hash);
如果(anchor.length==0){
锚定=$(“.tabs div:eq(0)”);
}
更新选项卡(锚定);
});
//传入选项卡并显示相应的内容
函数updateTabs(tab){
$(“.tabs#tab a”)
.removeClass(“活动”)
.过滤器(功能(索引){
返回$(this.attr(“href”)=='#'+tab.attr(“id”);
}).addClass(“主动”);
$(“.tabs.content”).hide();
tab.show();
}
//第一次加载页面时触发hashchange事件
$(window.trigger('hashchange');
第一组 第2组 第3组
为什么不使用CSS隐藏所有
.content
元素:

<style>
    .content { display: none; }
</style>

.content{显示:无;}
这将阻止浏览器在javascript接管之前显示任何
.content
元素


注意:如果用户访问您的网站时禁用了javascript,他们将看不到任何
.content
元素。

只需使用Jquery隐藏所有元素

<script>
    $('.content').hide();
</script>

$('.content').hide();
这将为每个元素设置Display为none,但如果禁用Javascript,用户可以使用所有内容。

对我来说效果很好。看见您是否有遇到问题的特定浏览器?你肯定包括jQuery吗?Javascript控制台中有错误吗?我使用Firefox并添加了$(document).ready(function(){jscode});它成功了。