Jquery - Select tab via url

后端 未结 4 819
既然无缘
既然无缘 2021-01-15 23:42

I have the following jquery code that allows me to use tabs, to tab back and fourth between content/divs. My question is using the code below, how could I have it load the i

4条回答
  •  太阳男子
    2021-01-16 00:19

    You can get the hash value in a url using window.location.hash. From there, you just need to do some slight checking to determine what tab should be shown.

    Here's a live example. Please note that we can't actually use window.location.hash in jsFiddle because it uses iFrames, which means the address you see in the browser's address bar isn't the value the code itself will get. Therefore, you can play around with it simply by setting the value of the hash variable directly in the code.

    Anyway, assume this is your HTML:

    One
    Two
    Three

    Then your JavaScript would be:

    $(function(){
    
        hash = window.location.hash
    
        index = parseInt(hash.replace('tab','')) - 1;
    
        if(isNaN(index)){ //if the hash isn't a valid tab
            index = 0;
        }
    
        $('div').eq(index).show();
    });
    

    You should probably also check first to make sure $('div').eq(index) actually exists, resorting to showing the first tab if it doesn't (just like we do if the hash analysis doesn't produce a legitimate value).

提交回复
热议问题