2011-09-06 116 views
1

我使用的是从Sohtanaka的jQuery切换效果,以便“显示”和“隐藏”内容。jQuery切换和锚链接

这是jQuery的:

$(document).ready(function(){ 

//Hide (Collapse) the toggle containers on load 
$(".toggle_container").hide(); 

//Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state) 
$("h2.trigger").click(function(){ 
    $(this).toggleClass("active").next().slideToggle("slow"); 
    return false; //Prevent the browser jump to the link anchor 
}); 

}); 

,这是我的HTML:

<h2 class="trigger"><a href="#test1">Test 1</a></h2> 
<div class="toggle_container"> 
    <div class="block"> 
    <h3>Content Header</h3> 
    <p>content</p> 
    </div> 
</div> 

<h2 class="trigger"><a href="#test2">Test 2</a></h2> 
<div class="toggle_container"> 
    <div class="block"> 
    <h3>Content Header</h3> 
    <p>content</p> 
    </div> 
</div> 

<h2 class="trigger"><a href="#test3">Test 3</a></h2> 
<div class="toggle_container"> 
    <div class="block"> 
    <h3>Content Header</h3> 
    <p>content</p> 
    </div> 
</div> 

一切正常。

我想知道什么需要修改,以便当相应的锚点位于url的末尾时显示特定的容器?

例如如果我的网址是“www.domain.com/content/#test2”,我希望显示容器“测试2”,并且“测试1”和“测试3”保持隐藏状态。

非常感谢。

回答

2

您应该能够将此功能像这样添加到您的代码:

$(document).ready(function() { 
    $(".toggle_container").hide(); 
    $("h2.trigger").click(function() { 
     $(this).toggleClass("active").next().slideToggle("slow"); 
     return false; //Prevent the browser jump to the link anchor 
    }); 

    $("a[href='" + window.location.hash + "']").parent(".trigger").click(); 
}); 
+0

这绝对是完美的,非常感谢您的快速回复和解释。 – Darren

+0

谢谢!如果你想允许书签,你不应该''返回false;'在你的触发器中点击以便散列可以存在。 – hunter

0

当URL为http://www.domain.com/content/#test2时,window.location.hash将保存值#test2。这是你应该在jQuery的属性选择用什么,你用它来准备处理程序中找到<a>元素:(Demo一个更优雅的实现是必然存在的。)

$(document).ready(function() { 
    ... 

    if (window.location.hash) { 
     $('h2.trigger + .toggle_container').hide(); // Hide all... 
     $('h2.trigger').has("a[href='" + window.location.hash + "']").next('.toggle_container').show(); // ... but show one 
    } 
}); 

更新
我我的第一个答案在很多方面是不正确的:-S

+0

这不是确切的jQuery选择器。这些值存储在'href'属性中,而不是'id'属性中。 –

0
$(document).ready(function() { 
    $('a').each(function() { 
     if($(this).attr('href') == window.location.hash) { 
      $(this).parent(".trigger").click(); 
     } 
    }); 
);