Change active tab on button click

2020-07-26 02:14发布

问题:

I have two tabs generated by jquery-ui. I do something in the Tab1 and on a button click, there is an AJAX call which displays the results in Tab2.

So I want to change the active tab on button click ( after the ajax call finishes ). Can I do so?

I've created a jsFiddle here


I tried onclick='$("#tabs-2").trigger("click") '> but it didn't do anything.

回答1:

Use onclick='$("#tabs").tabs( "select", "tabs-2" )'

http://jqueryui.com/demos/tabs/#method-select



回答2:

As info (in case someone stumbles upon this later and gets an error on the select method) - In jQuery-UI 1.9+, the select method was deprecated.

(http://jqueryui.com/upgrade-guide/1.9/#deprecated-select-method)

Use the option method, example:

$("#tabs").tabs("option", "active", 2);


回答3:

js fiddle

http://jsfiddle.net/maheshvemuri/M7Fdu/

Here is JS part of the code:

$(document) .ready(function() {
    $("#tabs").tabs(); 
    $(".btnNext").click(function () {
            $( "#tabs" ).tabs( "option", "active", $("#tabs").tabs('option', 'active')+1 );
        });
        $(".btnPrev").click(function () {
            $( "#tabs" ).tabs( "option", "active", $("#tabs").tabs('option', 'active')-1 );
        });
});

Here are the "a href" tags to be added in your tabs div

Example:

<div id="tabs-1">
<a class="myButton btnNext" style="color:white;">Next Tab</a>
</div>
<div id="tabs-2">
<a class="myButton btnPrev" style="color:white;">Previous Tab</a>
<a class="myButton btnNext" style="color:white;">Next Tab</a>
</div>
<div id="tabs-3">
<a class="myButton btnPrev" style="color:white;">Previous Tab</a>
</div>


回答4:

You have to make the trigger call to "a" inside the "li", not direct to the tab "div" like it's done.

<div id="tabs">     
    <ul>
        <li><a id="lnk1" href="#tabs-1">tab1</a></li>   
        <li><a id="lnk2" href="#tabs-2">tab2</a></li>             
    </ul>    
    <div id="tabs-1">
     <button type="button" id="clicktab2" onclick='$("#lnk2").trigger("click");'>
       go to tab2
     </button>
    </div>
    <div id="tabs-2">
     tab2 content 
    </div>
</div>

Example:

http://jsfiddle.net/Tf9sc/152/



回答5:

Also you can try

$(window).load(function(){
   $('#tabs-2').trigger('click');
});

that's because you cannot trigger call the tabs() in ready mode. document.ready is executed earlier than window.load.