Jquery - Select tab via url

后端 未结 4 818
既然无缘
既然无缘 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:10

    Detecting changes on the URL fragment (#whatever) is hard to do crossbrowser without a little help. I usually use Ben Alman's BBQ plugin:

    http://benalman.com/code/projects/jquery-bbq/examples/fragment-jquery-ui-tabs/

    If I'm misunderstanding and you just want to load a tab based on the INITIAL url, you could just do it by detecting the hash:

    ...
    if(window.location.hash){
      $(".tabs > li a[href=" + window.location.hash + "]").click();
    }
    

    This assumes that your tab is linking to href="#foo", and that the URL you visit is mysite.com/pagename#foo

    0 讨论(0)
  • 2021-01-16 00:12

    You can use gup function,found here:

    function gup( name )
    {
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( window.location.href );
      if( results == null )
        return "";
      else
        return results[1];
    }
    

    This will allow you to read a URL parameter and use it to navigate to the selected tab.

    0 讨论(0)
  • 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:

    <div>One</div>
    <div>Two</div>
    <div>Three</div>
    

    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).

    0 讨论(0)
  • 2021-01-16 00:20

    Hopefully this will help: -

    var tab_id = $(this).attr('href');
    var split = tab_id.split('#');
        split = split[1];
    
    if (split = "page 2") {
    
    window.alert(split);
    
    } else {
     // Default condition   
    
    }
    

    JS Fiddle Example here - http://jsfiddle.net/aNMBW/

    0 讨论(0)
提交回复
热议问题