有两种使用jQuery选择具有多个类的元素的过程。下面将以适当的示例描述这两个过程。
使用filter()方法:通过使用filter()方法, 我们可以过滤出所有不符合所选条件的元素, 并且将返回这些匹配项。
语法:$(选择器).filter(条件, 函数(索引))
例子:
<!DOCTYPE html>
< html >
< head >
< title >
jQuery | Select an element
with multiple classes
</ title >
< style >
h1 {
color: green;
}
body {
text-align: center;
}
</ style >
< script src =
"https://code.jquery.com/jquery-1.12.4.min.js" >
</ script >
</ head >
< body >
< h1 >lsbin</ h1 >
< h3 >
Select an element with
multiple classes
</ h3 >
< div class = "geeks" >lsbin</ div >
< div class = "geeks geeks1" >jQuery</ div >
< div class = "geeks1" >
Select an element with
multiple classes
</ div >
< div class = "geeks1 geeks" >Using</ div >
< div class = "geeks geeks1 geeks2" >
filter() method
</ div >
< script >
$(document).ready(function(){
$(".geeks").filter(".geeks1").css(
"background-color", "yellow");
$(".geeks.geeks2").filter(".geeks1")
.css("background-color", "green");
});
</ script >
</ body >
</ html >
输出如下:
使用.class选择器:通过使用.class Selector, 可以为要选择的元素指定类。它不能以数字开头。它为多个HTML元素提供样式。
语法:$("。class1.class2.class3 ...")
例子:
<!DOCTYPE html>
< html >
< head >
< title >
jQuery | Select an element
with multiple classes
</ title >
< style >
h1 {
color: green;
}
body {
text-align: center;
}
</ style >
< script src =
"https://code.jquery.com/jquery-1.12.4.min.js" >
</ script >
</ head >
< body >
< h1 >lsbin</ h1 >
< h3 >
Select an element with
multiple classes
</ h3 >
< div class = "geeks" >lsbin</ div >
< div class = "geeks geeks1" >jQuery</ div >
< div class = "geeks1" >
Select an element with
multiple classes
</ div >
< div class = "geeks1 geeks" >Using</ div >
< div class = "geeks geeks1 geeks2" >
.class Selector Method
</ div >
< script >
$(document).ready(function(){
$(".geeks1").css(
"background-color", "yellow");
$(".geeks").css(
"background-color", "white");
$(".geeks.geeks2").css(
"background-color", "green");
});
</ script >
</ body >
</ html >
输出如下: