天天看點

jQuery周遊 is() 方法和 toggleClass()的使用

2017年12月27日

jQuery周遊 is() 方法和 toggleClass()的使用

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="/jquery/jquery.js"></script>
<style>
.active {background-color: #f00;}
.active-warn {background-color: #ff0;}
</style>
</head>

<body>
<ul>
  <li><strong>list</strong> item 1 - one strong tag</li>
  <li><strong>list</strong> item <strong>2</strong> -
    two <span>strong tags</span></li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

<script>
$("li").click(function() {
  var $li = $(this),
    isWithTwo = $li.is(function() {
      return $('strong', this).length === 2;
    });
  if ( isWithTwo ) {
    $li.toggleClass("active-warn");
  } else {
    $li.toggleClass("active");
  }
});
</script>

</body>
</html>           

繼續閱讀