开发者

How do I get the text of the active

<div class="tabs">
<ul>
  <li class="active"><span class="l"></span><a href="#">Standard Class</a><span class="r"> </span></li>
<li><span class="l"></span><a href="#">Bussiness Class</a><span class="r"></span></li>
<li><span class="l"></span><a href="#">Premium</a><span class="r"></span></li>

and how to I take off the class active off the non sel开发者_如何学JAVAected one and put it on the selected one with jQuery


$('.tabs a').click(function() { 
 $('.tabs li').removeClass('active');
 (this).parent().addClass('active');
});

and for the text of the active:

$('.tabs .active a').text();


Try this:

It caches your <li> elements, so you don't need to keep selecting them from the DOM.

var $lis = $('div.tabs > ul > li').click(function() {
    var text = $(this).addClass('active').text();
    $lis.not(this).removeClass('active');
});


var activeText = $('.active a').text();


Live example: http://jsbin.com/uwigo4/3 (full source below)

Getting the text of the "active" one, you can use text:

var text = $('div.tabs li.active').text();

Changing which is the active one, you just removeClass and addClass as appropriate, e.g.:

jQueryObjForCurrentActiveElement.removeClass('active');
jQueryObjForNewElementToMakeActive.addClass('active');

If you're doing this in an event handler, odds are you'll want hasClass as well.

Source of live example:

<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Test Page</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type='text/javascript'>

jQuery(function($) {

  $('div.tabs > ul > li').click(function(event) {
    var $this = $(this);
    if (!$this.hasClass('active')) {
      display("Activating '" + $this.text() + "'");
      $('div.tabs li.active').removeClass('active');
      $this.addClass('active');
    }
  });

  function display(msg) {
    $('<p>' + msg + '</p>').appendTo(document.body);
  }

});​

</script>
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
  .active {
    font-weight: bold;
    background-color: #eee;
  }
</style>
</head>
<body>
  <div class='tabs'>
    <ul>
      <li class='active'><span>Tab 1</span></li>
      <li><span>Tab 2</span></li>
      <li><span>Tab 3</span></li>
    </ul>
  </div>
</body>
</html>​
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜