admin管理员组

文章数量:1403358

I hope somebody can help me to load the first tab (make it active) when the page is loaded. Now the jquery tabs only works fine after clicking.

I'm using this code:

HTML

<a class="link" href="#" rel="div1">Tab 1</a>
<a class="link" href="#" rel="div2">Tab 2</a>

<div class="content5" id="div1">Content of Tab 1</div>
<div class="content5" id="div2">Content of Tab 2</div>

Javascript/Jquery

$('.link').click(function(e) {
    e.preventDefault();
    var content = $(this).attr('rel');
    $('.active').removeClass('active');
    $(this).addClass('active');
    $('.content5').hide();
    $('#' + content).show();
});​

Any ideas?

I hope somebody can help me to load the first tab (make it active) when the page is loaded. Now the jquery tabs only works fine after clicking.

I'm using this code:

HTML

<a class="link" href="#" rel="div1">Tab 1</a>
<a class="link" href="#" rel="div2">Tab 2</a>

<div class="content5" id="div1">Content of Tab 1</div>
<div class="content5" id="div2">Content of Tab 2</div>

Javascript/Jquery

$('.link').click(function(e) {
    e.preventDefault();
    var content = $(this).attr('rel');
    $('.active').removeClass('active');
    $(this).addClass('active');
    $('.content5').hide();
    $('#' + content).show();
});​

Any ideas?

Share Improve this question edited Feb 28, 2012 at 13:06 Didier Ghys 30.6k9 gold badges76 silver badges82 bronze badges asked Feb 28, 2012 at 13:04 ErikdgErikdg 31 silver badge2 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 4
$(document).ready(function() {
    $('.link:first').addClass('active');
});

I would encapsulate the display logic;

function showTab(jqEl) {
    var content = jqEl.attr('rel');
    $('.active').removeClass('active');
    jqEl.addClass('active');
    $('.content5').hide();
    $('#' + content).show();
};

The call as needed;

$('.link').click(function(e) {
    e.preventDefault();
    showTab($(this));
});

and

$().ready(function() {
  showTab($(".link[rel=div1]")); //or better
});

You can trigger a click on the first link after the binding:

$('.link')
    .click(function(e) {
        ...
    })
    .first().click(); // or .trigger('click')

.click() / .trigger('click')

Just use HTML and CSS to make it visible, i.e:

Tab 1 Tab 2

Content of Tab 1 Content of Tab 2

So the first link starts out with a class of active, and the first tab starts out as visible via display:block.

Can you wrap the Code in a function? call the function from inside the event, passing in thr object $(this). Call the function on page load passing in ('.link').first()

i am not sure which jquery you are using but in simple way try to load the tab in page load as below:

 $(document).ready(function () {
            $("#tabs").tabs({ selected: 1 });
        });

本文标签: javascriptShow first tab when page is loadedStack Overflow