-->

Load page into a div with a specific jQuery UI tab

2019-09-08 04:10发布

问题:

I've got a page with some global navigation that loads other pages into a content div using jQuery. The pages I'm loading into the div have jQuery UI tabs on them. I know how to load the pages into the div, but what I want to do is load the pages with a specific tab panel selected/open. Here's the html for my base page:

<nav>
<a href="tabs.htm#tab-1">Link to Tab 1</a>
<a href="tabs.htm#tab-2">Link to Tab 2</a>
<a href="tabs.htm#tab-3">Link to Tab 3</a>
</nav>
<main></main> 

And the html for the tabs.htm page:

<div class="tabs nav-tabs">
<ul>
  <li><a href="#tab-1">Tab 1</a></li>
  <li><a href="#tab-2">Tab 2</a></li>
  <li><a href="#tab-3">Tab 3</a></li>
</ul>
<div id="tab-1">Blah</div>
<div id="tab-2">Blah</div>
<div id="tab-3">Blah</div>
</div>

And my script:

$('nav a').click(function(e){
e.preventDefault();
$('main').load(this.href, function() {
});

Is this possible?

回答1:

With your current setup, you can do the following using the active option of tabs widget:

$('nav a').click(function(e){
   e.preventDefault();
   var tabIndex = parseInt(--this.href.split('#tab-')[1],10);
   $('main').load(this.href, function() {
        $(this).find('.tabs').tabs({
            active: tabIndex
        })
   });
});

demo @ plnkr



回答2:

you can use method .show() and CSS Selectors. Here is how i get first tab (remember they are elements, you can use their id class or whatever):

e.g.:
$('#tabId a:first').tab('show');

or:
$('a#tab-item-id').tab('show');

So you could put this code on success function of $ajax for example.



回答3:

<div class="tabs nav-tabs">
<ul>
  <li><a href="link.html#tab-1">Tab 1</a></li>
  <li><a href="link.html#tab-2">Tab 2</a></li>
  <li><a href="link.html#tab-3">Tab 3</a></li>
</ul>
<div id="tab-1">Blah</div>
<div id="tab-2">Blah</div>
<div id="tab-3">Blah</div>
</div>


$('.nav-tabs a').click(function(e){
  var link = $(this).attr('href');
  var result = link.split('#');
  console.log( result[0] );  // link.html
  console.log( result[1] ); // tab-#
  $('a[href="'+ result[0] +'#' + result[1] + '"]').tab('show');
  $('#'+result[1]).load(result[0],function(){
    // do something
  });
  return false;
});

UPDATE

I'm not sure about this part $('a[href="'+ result[0] +'#' + result[1] + '"]').tab('show'); may be you will need to use another construction, for example <a href="link.html" data-target="#tab-1"></a>