Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

javascript - How to build simple tabs with jQuery?

I have the following code: fiddle

Which works great in websites I create my self and with no JS the tabs act as jump links to the relevant sections. When placed in the bespoke CMS I am forced to use at the moment the jump links don't work. I have tried adding more relative links to the tabs which makes it work with no JS but with JS the tabbed content doesn't show.

Am I missing something?

html:

<ul id="tabs">

      <li><a href="#tab1">test1</a></li>
      <li><a href="#tab2">test2</a></li>
      <li><a href="#tab3">test3</a></li>
      <li><a href="#tab4">test4</a></li>

</ul>
      <div class="container" id="tab1">Some content</div>
      <div class="container" id="tab2">Some content</div>
      <div class="container" id="tab3">Some content</div>
      <div class="container" id="tab4">Some content</div>

jQuery:

$('#tabs li a:not(:first)').addClass('inactive');
$('.container').hide();
$('.container:first').show();
$('#tabs li a').click(function(){
    var t = $(this).attr('href');
    $('#tabs li a').addClass('inactive');        
    $(this).removeClass('inactive');
    $('.container').hide();
    $(t).fadeIn('slow');
    return false;
})

if($(this).hasClass('inactive')){ //this is the start of our condition 
    $('#tabs li a').addClass('inactive');         
    $(this).removeClass('inactive');
    $('.container').hide();
    $(t).fadeIn('slow');    
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I am guessing your website is having problems with href, i presume that when user clicks a href, website automatically eradicating itself.

Here is new solution's jsFiddle.

I have a new solution for you:

updated jQuery:

$('#tabs li a').click(function(){
  var t = $(this).attr('id');

  if($(this).hasClass('inactive')){ //this is the start of our condition 
    $('#tabs li a').addClass('inactive');           
    $(this).removeClass('inactive');

    $('.container').hide();
    $('#'+ t + 'C').fadeIn('slow');
 }
});

new html markup:

<ul id="tabs">

      <li><a id="tab1">test1</a></li>
      <li><a id="tab2">test2</a></li>
      <li><a id="tab3">test3</a></li>
      <li><a id="tab4">test4</a></li>

</ul>
<div class="container" id="tab1C">1Some content</div>
<div class="container" id="tab2C">2Some content</div>
<div class="container" id="tab3C">3Some content</div>
<div class="container" id="tab4C">4Some content</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...