jQuery常用的 基本选择器

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_41684621/article/details/102747743

什么是jQuery选择器

jQuery选择器是jQuery为我们提供的一组方法,让我们更加方便的获取到页面中的元素。注意:jQuery选择器返回的是jQuery对象。

jQuery选择器有很多,基本兼容了CSS1到CSS3所有的选择器,并且jQuery还添加了很多更加复杂的选择器。【查看jQuery文档】

jQuery选择器虽然很多,但是选择器之间可以相互替代,就是说获取一个元素,你会有很多种方法获取到。所以我们平时真正能用到的只是少数的最常用的选择器。

css里的选择器jQuery都能写

基本选择器

名称 用法 描述
ID选择器 $(“#id”) $(“#id”) 获取指定ID的元素
类选择器 $(“.class”) 获取同一类class的元素
标签选择器 $(“div” 获取同一类标签的所有元素
并集选择器 $(“div,p,li”) 使用逗号分隔,只要符合条件之一就可。
交集选择器 $(“div.redClass”) 获取class为redClass的div元素

总结:跟css的选择器用法一模一样。
案例:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li id="four">4</li>
  <li>5</li>
  <li class="green yellow">6</li>
  <li class="green">7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
</ul>

<div class="green">111</div>
<div class="green">111</div>
<div class="green">111</div>
<div class="green">111</div>

<script src="jquery-1.12.4.js"></script>
<script>
  //入口函数
  $(function () {
    
    //jquery如何设置样式
    //css(name, value)
    //name:样式名  value:样式值
    
    //id选择器  $("#id")
    //$("#four").css("backgroundColor", "red");
  
  
    //$(".green").css("backgroundColor", "green");
  
  
    //$("li").css("color", "red");
  
  
    //交集
    //$("#four,.green").css("backgroundColor", "pink");


    //并集
    //$("li.green").css("backgroundColor", "red");
    $(".green.yellow").css("backgroundColor", "pink");
    
  });
  
  
</script>

</body>
</html>

注意: $(".green.yellow").css("backgroundColor", "pink");是并集选择器,对应获取的元素为

<li class="green yellow">6</li>

猜你喜欢

转载自blog.csdn.net/qq_41684621/article/details/102747743