如何使用jQuery添加类? [英] How to add class using jQuery?

查看:81
本文介绍了如何使用jQuery添加类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个小函数,当我们单击< li>时,它的工作是在<li>中添加类,但是如果<li>已经拥有它,我想删除它.

I made a small function whose work to do add class in <li> when we clicks on <li>, but I want to remove that if it is already had with <li>.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="generator" content="CoffeeCup HTML Editor (www.coffeecup.com)">
    <meta name="created" content="Tue, 22 May 2012 12:39:23 GMT">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <title></title>

    <style type="text/css">
    <!--
    body {
      color:#000000;
      background-color:#FFFFFF;
    }
    a  { color:#0000FF; }
    a:visited { color:#800080; }
    a:hover { color:#008000; }
    a:active { color:#FF0000; }
    -->
    </style>

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>

    <script type="text/javascript">

    $(function(){

    $('.main').find('li').each(function(){

    $(this).live('click', function (){

    $(this).addClass('active')

    })

    })

    })

    </script>

  </head>
  <body>

  <ul class="main">
  <li>first</li>

  <li>second</li>
    <li>third</li>
      <li>fourth</li>  

  </ul>

  </body>
</html>

推荐答案

您可以只使用toggleClass这将根据需要添加或删除它

You can just use toggleClass this will add or remove it as necessary

$('.main li').live('click',function(){
  $(this).toggleClass('active');
});

如果要从其他地方删除此类,则可以添加额外的一行:

if you want to remove this class from elsewhere, you can add an extra line:

$('.main li').live('click',function(){
  $('.main li.active').removeClass('active')
  $(this).addClass('active');
});

这篇关于如何使用jQuery添加类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆