简体   繁体   中英

jQuery Tab Menu Set Active Menu and load the content

I have jQuery tab menu call ajax.

Menu is working perfect, but now I want when page loaded it always show the first tab to be loaded (means active).

You can see the fiddle here: https://jsfiddle.net/waspinator/rw8ujfg3/

<ul class="nav nav-tabs tabs-up " id="friends">
  <li active><a href="/gh/gist/response.html/3843293/" data-target="#contacts" class="media_node active span" id="contacts_tab" data-toggle="tabajax" rel="tooltip"> Contacts </a></li>
  <li><a href="/gh/gist/response.html/3843301/" data-target="#friends_list" class="media_node span" id="friends_list_tab" data-toggle="tabajax" rel="tooltip"> Friends list</a></li>
  <li><a href="/gh/gist/response.html/3843306/" data-target="#awaiting_request" class="media_node span" id="awaiting_request_tab" data-toggle="tabajax" rel="tooltip">Awaiting request</a></li>

  <div class="tab-content">
  <div class="tab-pane active" id="contacts">

  </div>
  <div class="tab-pane" id="friends_list">
  </div>
  <div class="tab-pane  urlbox span8" id="awaiting_request">

  </div>
</div>

JS

$('[data-toggle="tabajax"]').click(function(e) {
var $this = $(this),
    loadurl = $this.attr('href'),
    targ = $this.attr('data-target');

$.get(loadurl, function(data) {
    $(targ).html(data);
});

$this.tab('show');
return false;
});

In this case, I want Contact content loaded on page loaded. How can set this?

This should work. Just abstract the function, and bind it to the event, but also call it on load with the first tab selected to call it on. ( EDIT : Sorry I got the spacing on your function wrong before because I mis-copied it. Also, tested it and changed a few things to work out a kink or two.)

function doAjaxStuff(event, tab) {
  var $this = tab || $(this)
    var $this = tab || $(this),
        loadurl = $this.attr('href'),
        targ = $this.attr('data-target');

    $.get(loadurl, function(data) {
        $(targ).html(data);
    });

    $this.tab('show');
    return false;
}

doAjaxStuff(null, $('.nav-tabs li:first-child a'))

$('[data-toggle="tabajax"]').click(doAjaxStuff);

$('#contacts_tab').trigger('click'); if you are allowed to use the id.

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