1. 程式人生 > >怎麽使用jquery判斷一個元素是否含有一個指定的類(class)

怎麽使用jquery判斷一個元素是否含有一個指定的類(class)

() pla jquer java 例子 add red tro lan

在jQuery中可以使用2種方法來判斷一個元素是否包含一個確定的類(class)。兩種方法有著相同的功能。2種方法如下:

1. is(‘.classname’)

2. hasClass(‘classname’)

以下是一個div元素是否包含一個redColor的例子:

1. 使用is(‘.classname’)的方法

$(‘div‘).is(‘.redColor‘)

2. 使用hasClass(‘classname’)的方法(註意jquery的低版本可能是hasClass(‘.classname’))

$(‘div‘).hasClass(‘redColor‘)

以下是檢測一個元素是否含有一個redColor類的例子,含有時,則把其類變為blueColor

<html>
<head>
<styletype="text/css">
  .redColor { 
        background:red;
  }
  .blueColor { 
        background:blue;
  }
</style>
<scripttype="text/javascript"src="jquery-1.3.2.min.js"></script>
</head>
<body
>
  <h1>jQuery check if an element has a certain class</h1>
 
  <divclass="redColor">This is a div tag with class name of "redColor"</div>
 
  <p>
  <buttonid="isTest">is(‘.redColor‘)</button>
  <buttonid="hasClassTest">hasClass(‘.redColor‘)</button>
  <buttonid="reset">reset</button>
  </p>
<scripttype="text/javascript">
 
    $("#isTest").click(function () {
 
          if($(‘div‘).is(‘.redColor‘)){
                $(‘div‘).addClass(‘blueColor‘);
          }
 
    });
 
    $("#hasClassTest").click(function () {
 
          if($(‘div‘).hasClass(‘redColor‘)){
                $(‘div‘).addClass(‘blueColor‘);
          }
 
    });
 
        $("#reset").click(function () {
          location.reload();
    });
 
 
</script>
</body>
</html>

初始效果:

技術分享

點擊is(‘.redColor‘)後的效果:

技術分享

點擊hasClass(‘redColor‘)的效果與點擊is(‘.redColor‘)後的效果相同,點擊reset的效果與初始效果相同。

怎麽使用jquery判斷一個元素是否含有一個指定的類(class)