使用location.hash激活jQuery切换/slideToggle [英] Using location.hash to activate jquery toggle/slideToggle

查看:120
本文介绍了使用location.hash激活jQuery切换/slideToggle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用jquery toggle和slideToggle的列表的列表,这样,当单击项目时,说明性文本会滑出,并且类会在h3上更改.这些项目的html如下:

I have a list of a list that uses jquery toggle and slideToggle so that when items are clicked on, explanatory text slides out and the class changes on the h3. The html for the items looks like:

<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文件,然后将其写在标题中:

I included the jquery files and then write this in the header:

<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滑出.它工作正常.

This makes it so that if a link is clicked on, it will toggle the class change of the h3, the display:block/display:inline and the sliding out of the div. It works fine.

但是,现在我想要它,以便使用index.php#feature1之类的URL来激活该列表项的切换,就好像单击它一样.我知道我需要使用location.hash,但是我不确定该怎么做.我应该从哪里开始?

BUT, now I want it so that with a url like index.php#feature1, the toggling for that list item will be activated as if it'd been clicked on. I know I need to use location.hash but I'm not sure how to do that. Where should I start?

推荐答案

包含URL中的所有内容,包括井号(#)和井号(#)之后.因此,如果转到index.php#feature1并希望ID为"feature1"的div在加载时显示,则可以

location.hash contains everything in the URL including and after the hash (#) mark. So, if went to index.php#feature1 and wanted the div with id "feature1" to show on load, you could do

$(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)
        }
    }
});

这篇关于使用location.hash激活jQuery切换/slideToggle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆