简体   繁体   中英

jQuery UI Tabs: Targeting Dynamic Tab from a Link

Recently I've been looking at opening a tab using this script:

$('.tofour').click(function() { // bind click event to link
    $tabs.tabs('select', 3); // switch to third tab
    return false;
});

However my specific problem is that the site I'm working on does not always load the same tab set. The tabs can change dependent on whether certain information exists. Example:

In certain situations we'll have enough data for:

  1. Product Data (#overview)
  2. Specifications (#specs)
  3. Accessories (#accessories)
  4. Services (#services)
  5. Customer Reviews (#reviews)

And in other situations there will be only enough data to populate two tabs

  1. Product Data (#overview)
  2. Accessories (#accessories)

As you can imagine this creates a problem as the tab number can change; the Specification tab ( #specs ) might be either the second tab, or the first tab (if Product Data doesn't exist), or Specifications tab might not exist at all.

So, for the sake of argument, lets say I wish to target the Specifications tab. I guess the first thing would be to check if the div id #specs exists. Then I guess I've got to create a link that will target that. But can I target an id instead of a tab number, as in the usual example (above)?

Can anyone help with this? My jQuery skills are, I'm ashamed to admit, pretty poor.

I thank you kindly in advance.

You could get the index via this code, then check if it's -1 (that means it doesn't exist)

Note: This assumes that the a tag for the tab has the id of specs

var index = $('#tabs a').index($('#specs'));

if (index > -1) {
    $('#tabs').tabs('select', index);
}
$("#m").live('click',function(){
    $('#tabs').tabs({ selected: "#tabs-1" });
});

Try this. Let me know further.

Create a javascript array containing the tab id as the key and the tab index as the value:

// if you're using php and the tabs that need to be generated are in a variable called $tabs
// you could work this out in other languages
$count = count($tabs);
for($i=0;$i<=$count;$i++){
    $tab = $tabs[$i];
    echo 'tab_indexes[' . $tab['id'] . '] = ' . $i . ';'; // id as in #specs, etc
}

Then use the array in jQuery:

$('#to_specs').click(function() { // bind click event to link
    $('#tabs').tabs('select', tab_indexes['#specs']); // switch to specs tab
    return false;
});

This should be good for the scenario You can replace element.id.match('specs') with your desired condition

$('.tofour').click(function(evt) {
   $('#tabs a').each(function(index,element){
     if(index != -1 && element.id.match('specs')){
     $('#tabs').tabs('select', index);
     return false;
     }
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM