Using location.hash to activate jquery toggle/slideToggle

◇◆丶佛笑我妖孽 提交于 2019-12-10 11:07:06

问题


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>

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>

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.

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?


回答1:


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


来源:https://stackoverflow.com/questions/6700276/using-location-hash-to-activate-jquery-toggle-slidetoggle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!