使用location.hash来激活jQuery切换/ slideToggle
我有一个使用jQuery切换和slideToggle的列表的列表,以便当项目被点击时,说明性文字滑出,并且类在h3上发生变化。对于项目的HTML如下:使用location.hash来激活jQuery切换/ slideToggle
<li><h3><a href="#" target="_blank" id="feature1" name="feature1">What do I know about javascript?</a></h3>
<div class="check_list_wrap feature1">Not a lot, apparently.</div>
</li>
我包括jQuery的文件,然后写这篇文章的标题:
<script type="text/javascript">
$(function() {
$("#listfeatures h3 a").toggle(function(){
$(this).addClass("check_list_selected");
}, function() {
$(this).removeClass("check_list_selected");
});
$("#listfeatures h3 a").click(function() {
$("."+this.id).slideToggle('fast');
return false;
});
});
</script>
这使得它,这样如果用户点击一个链接时,就会切换h3的类更改,display:block/display:inline和滑出div。它工作正常。
但是,现在我想让它像index.php#feature1这样的url,那个列表项的切换将被激活,就像它被点击一样。我知道我需要使用location.hash,但我不知道该怎么做。我应该从哪里开始?
location.hash
包含URL中的所有内容以及散列(#)标记之后。所以,如果去的index.php#特征1和希望ID为“特征1”的div来显示上的负载,你可以做
$(document).ready(function() {
if(location.hash) {
var id = location.hash.slice(1); //Get rid of the # mark
var elementToShow = $("#" + id); //Save local reference
if(elementToShow.length) { //Check if the element exists
elementToShow.slideToggle('fast'); //Show the element
elementToShow.addClass("check_list_selected"); //Add class to element (the link)
}
}
});
这工作正常,除了在h3上的类没有改变。我怎样才能做到这一点? –
只需在if的主体中添加'$(“。”+ id).addClass(“check_list_selected”);'。我会编辑答案。 –
这改变了check_list_wrap上的类,我试图改变它上面的h3上的类 –
我敢肯定,你需要到'onload'事件,以便响应新的点击将为你的脚本注册一些东西来回应。诀窍是该页面并未真正重新加载,但您仍然可以获得该事件。 – ErikE