2016-01-13 57 views
0

我是新来的JavaScript和使用jQuery切换效果的按钮来打开和关闭下面的div。这里是我的html:页面加载时使用散列链接无效的切换元素

<article id="book-section"> 
<h3>The new collection</h3> 
<a class="btn" href="#book-list-one">Book list</a> 
<div> 
<ul> 
    <li>Book one</li> 
    <li>Book two</li> 
    <li>Book three</li> 
    <li>Book four</li> 
</ul> 
</div> 
</article> 

这里是我的javascript

$(document).ready(function() { 
$(".btn").click(toggle); 
function toggle() { 
    { 
     $(this).toggleClass("open").next().slideToggle(); 
     return false; 
    }; 

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

它应该是开放的div包含图书列表时的index.html#用户类型的书列表之一,但它没有。切换效果工作得很好。我无法弄清楚问题是什么。任何帮助,将不胜感激!!! 在此先感谢!

更新:这里是JSfiddle

+0

只是增加了一个的jsfiddle。希望有所帮助。 – Maya

回答

0

您已经闭架的功能设置不正确:

$(document).ready(function() { 

    $(".btn").click(toggle); 

    function toggle() { 
    $(this).toggleClass("open").next().slideToggle(); 
    return false; 
    } 

    // and seems like the a tag in html snippet posted 
    // doesn't have parent with the class name `.btn`, 
    // $("a[href='" + window.location.hash + "']").parent(".btn").click(); 
    // instead try access it directly 
    $("a[href='" + window.location.hash + "']").click(); 

}); 
+0

不幸的是,这并不适用于我。 – Maya

+0

你确定在你的代码中的'window.location.hash'从url返回正确的哈希?因为当我将哈希URL直接编码到标记中时,它可以正常工作。在这里查看你的更新小提琴https://jsfiddle.net/norlihazmeyGhazali/pdz92ms7/ –

相关问题