Show first tab when page is loaded

Deadly 提交于 2019-12-11 20:39:45

问题


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?


回答1:


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



回答2:


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
});



回答3:


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

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

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




回答4:


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.




回答5:


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()




回答6:


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 });
        });


来源:https://stackoverflow.com/questions/9482440/show-first-tab-when-page-is-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!