jQuery 编程 | 02 - jQuery 选择器

一、基础选择器

All Selector ("*")

选择所有元素,此选择器使用要慎重,其速度是极其慢的

<!DOCTYPE html>
<html>
<head>
  <style>
  h3 { margin: 0; }
  div,span,p {
    width: 80px;
    height: 40px;
    float:left;
    padding: 10px;
    margin: 10px;
    background-color: #EEEEEE;
  }
  #test {
    width: auto; height: auto; background-color: transparent;
  }
  </style>
  <script src="./jquery-3.6.0.min.js"></script>
</head>
<body>
  <div id="test">
  <div>DIV</div>
  <span>SPAN</span>
  <p>P <button>Button</button></p>
</div>
<script>
var elementCount = $("#test").find("*").css("border","3px solid red").length;
$("body").prepend("<h3>" + elementCount + " elements found</h3>");</script>
 
</body>
</html>
复制代码

Class Selector (".class")

选择给定样式类名的所有元素。

<!DOCTYPE html>
<html>
<head>
  <style>
  div,span {
    width: 100px;
    height: 40px;
    float:left;
    padding: 10px;
    margin: 10px;
    background-color: #EEEEEE;
  }
  </style>
  <script src="./jquery-3.6.0.min.js"></script>
</head>
<body>
  <div class="notMe">div class="notMe"</div>
 
  <div class="myClass">div class="myClass"</div>
  <span class="myClass">span class="myClass"</span>
<script>$(".myClass").css("border","3px solid red");</script>
 
</body>
</html>
复制代码

Element Selector ("element")

根据给定(html)标记名称选择所有的元素。

<!DOCTYPE html>
<html>
<head>
  <style>
  div,span {
    width: 60px;
    height: 60px;
    float:left;
    padding: 10px;
    margin: 10px;
    background-color: #EEEEEE;
  }
  </style>
  <script src="./jquery-3.6.0.min.js"></script>
</head>
<body>
  <div>DIV1</div>
 
  <div>DIV2</div>
  <span>SPAN</span>
<script>$("div").css("border","9px solid red");</script>
 
</body>
</html>
复制代码

ID Selector ("#id")

选择一个具有给定id属性的单个元素。

<!DOCTYPE html>
<html>
<head>
  <style>
  div {
    width: 90px;
    height: 90px;
    float:left;
    padding: 5px;
    margin: 5px;
    background-color: #EEEEEE;
  }
  </style>
  <script src="./jquery-3.6.0.min.js"></script>
</head>
<body>
  <div id="notMe"><p>id="notMe"</p></div>
 
  <div id="myDiv">id="myDiv"</div>
<script>$("#myDiv").css("border","3px solid red");</script>
 
</body>
</html>
复制代码

Child Selector ("parent > child")

选择所有指定“parent”元素中指定的"child"的直接子元素。

<!DOCTYPE html>
<html>
<head>
  <style>
body { font-size:14px; }
</style>
  <script src="./jquery-3.6.0.min.js"></script>
</head>
<body>
 
<ul class="topnav">
  <li>Item 1</li>
  <li>Item 2
    <ul><li>Nested item 1</li><li>Nested item 2</li><li>Nested item 3</li></ul>
  </li>
  <li>Item 3</li>
</ul>
 
<script>$("ul.topnav > li").css("border", "3px double red");</script>
 
</body>
</html>
复制代码

猜你喜欢

转载自juejin.im/post/7128793300231782431