質問

I ran into this problem that if I toggleClass on the same container using different links trying to show different content it wont show the container on any second link right away. Basically it will close the container and then I would have to click the link once again in order to show the content. I am trying to achieve tabs effect using the same container and toggleClass and unfortunately I can't figure out of how to show the container right away on second link. I would appreciate any advice.

Here is a live example http://jsbin.com/eyEnEvEC/1/

and the entire code.

CSS

.container {
  display:none;
}


.show {
  display:block;
}

HTML

<a href="" id="link1">Link 1</a>
<a href="" id="link2">Link 2</a> 
<div class="container"></div>

Javascript

$(function(){

  $('#link1').click(function(){    
    $('.container').html('Test 1');
    $('.container').toggleClass('show');
        return false;
  });

  $('#link2').click(function(){    
    $('.container').html('Test 2');
    $('.container').toggleClass('show');
        return false;
  });

});
役に立ちましたか?

解決

Try this

HTML

<a href="" id="link1" data-status="inactive">Link 1</a>
<a href="" id="link2" data-status="inactive">Link 2</a>

JQuery

$(function(){
  $.fn.toggleContent = function(ahtml) {
    var cstatus =  $(this).attr("data-status");
    $("a[id^=link]").attr("data-status","inactive");
    if(cstatus == "inactive") {
      $('.container').html(ahtml).show(); 
      $(this).attr("data-status","active");
    }
    else {
      $('.container').html(ahtml).hide();  
      $(this).attr("data-status","inactive");
    }
    return false;
  };

  $('#link1').click(function(){    
    $(this).toggleContent('Test 1');    

  });

  $('#link2').click(function(){    
    $(this).toggleContent('Test 2'); 
  });

});

Demo : http://jsbin.com/eyEnEvEC/9/edit

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top