developer tip

jQuery UI 탭-현재 선택된 탭 인덱스를 얻는 방법

optionbox 2020. 8. 2. 18:23
반응형

jQuery UI 탭-현재 선택된 탭 인덱스를 얻는 방법


이 특정 질문이 전에 요청 되었음을 알고 있지만 플러그인 bind()이벤트를 사용하여 결과를 얻지 못했습니다 jQuery UI Tabs.

index탭을 클릭했을 때 작업을 수행하려면 새로 선택한 탭이 필요합니다 . bind()select 이벤트에 연결할 수 있지만 현재 선택한 탭을 얻는 일반적인 방법은 작동하지 않습니다. 새 인덱스가 아닌 이전에 선택한 탭 인덱스를 반환합니다.

var selectedTab = $("#TabList").tabs().data("selected.tabs");

다음은 현재 선택된 탭을 얻는 데 사용하려는 코드입니다.

$("#TabList").bind("tabsselect", function(event, ui) {

});

이 코드를 사용하면 ui 객체가 다시 나타납니다undefined . 설명서에서 ui.tab을 사용하여 새로 선택한 인덱스에 연결하는 데 사용하는 객체 여야합니다. 나는 초기 tabs()통화와 자체적으로 이것을 시도했다 . 내가 여기서 잘못하고 있습니까?


1.9 이전의 JQuery UI 버전의 경우 : ui.index에서 event원하는 것입니다.

JQuery UI 1.9 이상 : 아래 Giorgio Luparia 답변참조하십시오 .


탭 이벤트 컨텍스트 외부에서 탭 색인을 가져와야 할 경우 다음을 사용하십시오.

function getSelectedTabIndex() { 
    return $("#TabList").tabs('option', 'selected');
}

업데이트 : 버전 1.9부터 '선택됨'이 '활성'으로 변경되었습니다.

$("#TabList").tabs('option', 'active')

UPDATE [ 일 2012년 8월 26일은 ]이 대답은 내가 본격적인 블로그로하기로 결정 정도로 인기를 끌고있다 / 튜토리얼을
참조하십시오 여기에 내 블로그 작업에 쉽게 접근 할 정보의 최신을 볼 jQueryUI에
또한 포함 (블로그에서도) jsFiddle입니다


¡ ¡ ¡ 업데이트! 참고 : 최신 버전의 jQueryUI (1.9+)에서는 ui-tabs-selected로 대체되었습니다 ui-tabs-active. !!!


이 스레드가 오래 되었다는 것을 알고 있지만 언급하지 않은 것은 "탭 이벤트"이외의 곳에서 "선택된 탭"(현재 드롭 다운 패널)을 얻는 방법이었습니다. 나는 간단한 방법이 있습니다 ...

var curTab = $('.ui-tabs-panel:not(.ui-tabs-hide)');

그리고 색인을 쉽게 얻으려면 물론 사이트에 나열된 방법이 있습니다 ...

var $tabs = $('#example').tabs();
var selected = $tabs.tabs('option', 'selected'); // => 0

그러나 첫 번째 방법을 사용하여 색인과 해당 패널에 대해 원하는 것을 얻을 수 있습니다 ...

var curTab = $('.ui-tabs-panel:not(.ui-tabs-hide)'),
    curTabIndex = curTab.index(),
    curTabID = curTab.prop("id"),
    curTabCls = curTab.attr("class");
        //  etc ....

추신. iframe 변수를 사용하고 .find ( '. ui-tabs-panel : not (.ui-tabs-hide)')를 사용하면 선택한 탭에 대해 프레임에서 쉽게 수행 할 수 있습니다. jQuery는 이미 모든 노력을 다 했으므로 휠을 재발 명할 필요가 없습니다!

확장하기 만하면 (업데이트 됨)

"보기에 두 개 이상의 탭 영역이 있으면 어떻게됩니까?" 다시 한 번, 간단하게 생각하고 동일한 설정을 사용하지만 ID를 사용하여 보유하려는 탭을 식별하십시오.

예를 들어 다음과 같은 경우

$('#example-1').tabs();
$('#example-2').tabs();

그리고 두 번째 탭의 현재 패널 세트를 원합니다.

var curTabPanel = $('#example-2 .ui-tabs-panel:not(.ui-tabs-hide)');

그리고 당신이 패널이 아닌 ACTUAL 탭을 원한다면 (정말 쉬워서 전에 언급하지 않았지만 지금은 철저히하기를 원합니다)

// for page with only one set of tabs
var curTab = $('.ui-tabs-selected'); // '.ui-tabs-active' in jQuery 1.9+

// for page with multiple sets of tabs
var curTab2 = $('#example-2 .ui-tabs-selected'); // '.ui-tabs-active' in jQuery 1.9+

다시 한 번, jQuery는 모든 노력을 다했다는 것을 기억하십시오. 그렇게 열심히 생각하지 마십시오.


JQuery UI 버전 1.9.0 이상을 사용하는 경우 함수 내에서 ui.newTab.index ()에 액세스 하여 필요한 것을 얻을 수 있습니다.

이전 버전의 경우 ui.index를 사용 하십시오 .


UI 개체에 언제 액세스하려고합니까? 바인드 이벤트 외부에서 액세스하려고하면 ui가 정의되지 않습니다. 또한이 줄이

var selectedTab = $("#TabList").tabs().data("selected.tabs");

다음과 같은 경우에 실행됩니다.

$("#TabList").bind("tabsselect", function(event, ui) {
  var selectedTab = $("#TabList").tabs().data("selected.tabs");
});

selectedTab은 해당 시점의 현재 탭과 동일합니다 ( "이전"이벤트). 클릭 한 탭이 ​​현재 탭이되기 전에 "tabsselect"이벤트가 호출되기 때문입니다. 그래도이 방법을 사용하려면 대신 "tabsshow"를 사용하면 selectedTab이 클릭 한 탭과 같습니다.

However, that seems over-complex if all you want is the index. ui.index from within the event or $("#TabList").tabs().data("selected.tabs") outside of the event should be all that you need.


var $tabs = $('#tabs-menu').tabs();
// jquery ui 1.8
var selected = $tabs.tabs('option', 'selected');
// jquery ui 1.9+
var active = $tabs.tabs('option', 'active');

this changed with version 1.9

something like

 $(document).ready(function () {
            $('#tabs').tabs({
                activate: function (event, ui) {
                    var act = $("#tabs").tabs("option", "active");
                    $("#<%= hidLastTab.ClientID %>").val(act);
                    //console.log($(ui.newTab));
                    //console.log($(ui.oldTab));
                }
            });

            if ($("#<%= hidLastTab.ClientID %>").val() != "") 
            {
                $("#tabs").tabs("option", "active", $("#<%= hidLastTab.ClientID %>").val());
            }


        });

should be used. This is working fine for me ;-)


In case anybody has tried to access tabs from within an iframe, you may notice it's not possible. The div of the tab never gets marked as selected, just as hidden or not hidden. The link itself is the only piece marked as selected.

<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-focus"><a href="#tabs-4">Tab 5</a></li>

The following will get you the href value of the link which should be the same as the id for your tab container:

jQuery('.ui-tabs-selected a',window.parent.document).attr('href')

This should also work in place of: $tabs.tabs('option', 'selected');

It's better in the sense that instead of just getting the index of the tab, it gives you the actual id of the tab.


the easiest way of doing this is

$("#tabs div[aria-hidden='false']");

and for index

$("#tabs div[aria-hidden='false']").index();

In case if you find Active tab Index and then point to Active Tab

First get the Active index

var activeIndex = $("#panel").tabs('option', 'active');

Then using the css class get the tab content panel

// this will return the html element
var element=   $("#panel").find( ".ui-tabs-panel" )[activeIndex]; 

now wrapped it in jQuery object to further use it

 var tabContent$ = $(element);

here i want to add two info the class .ui-tabs-nav is for Navigation associated with and .ui-tabs-panel is associated with tab content panel. in this link demo in jquery ui website you will see this class is used - http://jqueryui.com/tabs/#manipulation


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

then you will have the index of tab from 0

simple


Try the following:

var $tabs = $('#tabs-menu').tabs();

var selected = $tabs.tabs('option', 'selected');

var divAssocAtual = $('#tabs-menu ul li').tabs()[selected].hash;

I found the code below does the trick. Sets a variable of the newly selected tab index

$("#tabs").tabs({
    activate: function (e, ui) {
        currentTabIndex =ui.newTab.index().toString();
    }
});

You can post below answer in your next post

var selectedTabIndex= $("#tabs").tabs('option', 'active');

Another way to get the selected tab index is:

var index = jQuery('#tabs').data('tabs').options.selected;

$("#tabs").tabs({  
    load:  function(event, ui){  
        var anchor = ui.tab.find(".ui-tabs-anchor");  
        var url = anchor.attr('href');  
    }  
});  

In the url variable you will get the current tab's HREF / URL


take a hidden variable like '<input type="hidden" id="sel_tab" name="sel_tab" value="" />' and on each tab's onclick event write code like ...

<li><a href="#tabs-0" onclick="document.getElementById('sel_tab').value=0;" >TAB -1</a></li>
<li><a href="#tabs-1" onclick="document.getElementById('sel_tab').value=1;" >TAB -2</a></li>

you can get the value of 'sel_tab' on posted page. :) , simple !!!


If you want to ensure ui.newTab.index() is available in all situations (local and remote tabs), then call it in the activate function as the documentation says:

$("#tabs").tabs({
        activate: function(event, ui){
             alert(ui.newTab.index());
             // You can also use this to set another tab, see fiddle...
             // $("#other-tabs").tabs("option", "active", ui.newTab.index());                   
        },
});

http://jsfiddle.net/7v7n0v3j/


$("#tabs").tabs({
    activate: function(event, ui) {
        new_index = ui.newTab.index()+1;
        //do anything
    }
});

참고URL : https://stackoverflow.com/questions/300078/jquery-ui-tabs-how-to-get-currently-selected-tab-index

반응형