Selecting a jQuery Tab using a parameter in the URL

前端 未结 5 962
太阳男子
太阳男子 2020-12-02 23:35

I am currently investigating replacing the tabs provided by a Struts 1 tag library with the tabs provided by jQuery UI. I have successfully managed to get the tabs integrate

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 00:20

    I've got a slightly different approach that doesn't necessarily rely on the built-in select() function, but does use the livequery plugin:

    http://plugins.jquery.com/project/livequery/

    which is a more powerful version of the jQuery live function. It can easily bind future elements that match a query.

    Suppose you have a tabs structure as follows:

    
    

    ideally, you want a URL structure like this:

    mydomain/mypage?tab=tab2
    

    it becomes quite tricky because the select() method only supports integer indices, and what happens when you change your tabs around?

    Supposing you can get the url parameter into a variable as indicated above to do the following:

    First you locate your target element and add a class to it:

    jQuery('a#' + param).addClass('selectMe');
    

    Next you bind a livequery function to the element:

    jQuery('.ui-tabs-nav a.selectMe').livequery(function(){
     jQuery(this).removeClass('selectMe').triggerHandler('click');
    });
    

    This will match it only once it's been tab-ified and virtually 'click' it.

    Then, you can call your tabs function with no parameters:

    jQuery(".Tabs").tabs();
    

    and once it's complete, the tab will automatically be clicked and selected!

    Better yet, you can bind the tabs creation to livequery itself:

    jQuery(".Tabs").livequery(function(){
        jQuery(this).tabs();    
    });
    

    so that any elements you have with class '.Tabs' will automatically be converted into tabs upon load, now or in the future!

提交回复
热议问题