Elegant jQuery (Selectors and Chaining)

content

1. jQuery Basic Selector

2. Level selector

3. jQuery implicit iteration

4. jQuery filter selector

5. jQuery filter method

6. Sina drop-down menu case

7. jQuery's exclusive approach

8. Taobao clothing boutique case

9. jQuery chain programming


1. jQuery Basic Selector

$( "选择器" )  //里面选择器直接写CSS选择器即可,但是要加引号
name usage describe
ID selector $("#id") Get the element with the specified ID
full class selector $('*') match all elements
class selector $(".class") Get elements of the same class
Tag selector $("div") Get all elements of the same class tag
union selector $("div,p,li") select multiple elements
intersection selector $("li.current") intersection element
<body>
    <div class="nav"></div>
    <script>
        $(function() {
           $(".nav");
        })
    </script>
</body>

Getting an element with jQuery is that simple


2. Level selector

name usage describe
offspring selector $("ul>li"); Use the > sign to get elements at the parent-child level; note that the elements at the grandchild level will not be obtained
 
descendant selector $("ul li"); Use spaces, representing descendant selectors, to get all Ii elements under uI, including grandchildren, etc.
 


3. jQuery implicit iteration

Let's talk about how to set styles with jquery:

$('div').css('属性','值')

Now we have four sky blue div boxes, what should we do to make their background color red?

Previous methods of manipulating DOM elements:

var div = document.querySelectorAll('div');
for(var i = 0;i<div.length;i++)
{
    div[i].style.backgroundColor = 'red';
}

jquery practice:

$(function() {
      $('div').css("backgroundColor","red");
})

After learning the direct sentence, jquery is really fragrant, even the for loop is saved, because of the implicit iteration

So what exactly is implicit iteration?

The process of traversing internal DOM elements (stored in pseudo-array form) is called implicit iteration.

Simple understanding: traverse all the matched elements and execute the corresponding method, instead of looping again, simplifying our operations and making it easier for us to call.


4. jQuery filter selector

grammar usage describe
:first $('li:first') get the first li element
:last $('li:last') get the last i element
:eq(index) $("li:eq(2)") Among the obtained li elements, select the element with index number 2, and the index number starts from 0.
:odd $("li:odd") Among the t elements, select the element with an odd index number
:even $("li:even") Among the obtained Ii elements, select the element with an even index number


5. jQuery filter method

grammar usage illustrate
parent() $("li").parent(); Find parent (nearest level parent)
children(selector) $("ul").children("li") Equivalent to $("ul>li"), the nearest level (pro-son)
find(selector) $("ul").find("li"); Equivalent to $("ul li"), descendant selector
siblings(selector) $(".first").siblings("li"); Find sibling nodes, excluding itself
nextAll([expr]) $(".first").nextAll() Find all sibling elements after the current element
prevtAll([expr]) $(".last").prevAll() Find all sibling elements before the current element
hasClass(class) $('div').hasClass("protected") Checks whether the current element contains a specific class, if so, returns true
eq(index) $("li").eq(2); Equivalent to $("li:eq(2)"), index starts from 0


6. Sina drop-down menu case

 Sample code: 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        li {
            list-style-type: none;
        }
        a {
            text-decoration: none;
            font-size: 14px;
        }
        .nav {
            margin: 100px;
        }
        .nav>li {
            position: relative;
            float: left;
            width: 80px;
            height: 41px;
            text-align: center;
        }
        .nav li a {
            display: block;
            width: 100%;
            height: 100%;
            line-height: 41px;
            color: #333;
        }
        .nav>li>a:hover {
            background-color: #eee;
        }
        .nav ul {
            display: none;
            position: absolute;
            top: 41px;
            left: 0;
            width: 100%;
            border-left: 1px solid #FECC5B;
            border-right: 1px solid #FECC5B;
        }
        .nav ul li {
            border-bottom: 1px solid #FECC5B;
        }
        .nav ul li a:hover {
            background-color: #FFF5DA;
        }
    </style>
    <script src="jquery.min.js"></script>
</head>
<body>
    <ul class="nav">
        <li>
            <a href="#">微博</a>
            <ul>
                <li><a href="">私信</a></li>
                <li><a href="">评论</a></li>
                <li><a href="">@我</a></li>
            </ul>
        </li>
        <li>
            <a href="#">微博</a>
            <ul>
                <li><a href="">私信</a></li>
                <li><a href="">评论</a></li>
                <li><a href="">@我</a></li>
            </ul>
        </li>
        <li>
            <a href="#">微博</a>
            <ul>
                <li><a href="">私信</a></li>
                <li><a href="">评论</a></li>
                <li><a href="">@我</a></li>
            </ul>
        </li>
        <li>
            <a href="#">微博</a>
            <ul>
                <li><a href="">私信</a></li>
                <li><a href="">评论</a></li>
                <li><a href="">@我</a></li>
            </ul>
        </li>
    </ul>
    <script>
        $(function() {
            // 鼠标经过
            $(".nav>li").mouseover(function() {
                // $(this) jQuery 当前元素  this不要加引号
                // show() 显示元素  hide() 隐藏元素
                $(this).children("ul").show();
            });
            // 鼠标离开
            $(".nav>li").mouseout(function() {
                $(this).children("ul").hide();
            })
        })
    </script>
</body>
</html>

7. jQuery's exclusive approach

If there are four black div boxes now, and we want to realize which box is clicked, which box will turn red, what should we do?

In our native js, should a for loop add a click event to each box, and then a for loop will first clear all styles, that is, exclusive, and then change the current box color to red.

Then let's take a look at how js does it, which can be implemented very simply through implicit iteration:

$(function() {
      // 1. 隐式迭代 给所有的按钮都绑定了点击事件
      $("div").click(function() {
      // 2. 当前的元素变化背景颜色
      $(this).css("background", "red");
      // 3. 其余的兄弟去掉背景颜色 隐式迭代
      $(this).siblings("div").css("background", "");
      });
})

8. Taobao clothing boutique case

Realize the effect:

case analysis:

  • 核心原理:鼠标经过左侧盒子某个小li ,就让内容区盒子相对应图片际,其余的图片隐藏。
  • 需要得到当前小li的索引号,就可以显示对应索引号的图片
  • jQuery得到当前元素索引号$(this).index()
  • 中间对应的图片,可以通过eq(index)方法去选择
  • 显元素show() 隐藏元素hide()
$(function() {
      // 1. 鼠标经过左侧的小li 
      $("#left li").mouseover(function() {
      // 2. 得到当前小li 的索引号
      var index = $(this).index();
      console.log(index);
      // 3. 让我们右侧的盒子相应索引号的图片显示出来就好了
      $("#content div").eq(index).show();
      // 4. 让其余的图片(就是其他的兄弟)隐藏起来
      $("#content div").eq(index).siblings().hide();
     })
})

9.jQuery链式编程

在我们的第七小节里有这样一段代码:

$(function() {
      // 1. 隐式迭代 给所有的按钮都绑定了点击事件
      $("div").click(function() {
      // 2. 当前的元素变化背景颜色
      $(this).css("background", "red");
      // 3. 其余的兄弟去掉背景颜色 隐式迭代
      $(this).siblings("div").css("background", "");
      });
})

第二步是让当前元素变化背景颜色

第三步是让当前元素的兄弟去掉背景颜色

那我们可不可以简写呢?

链式编程是为了节省代码量,看起来更优雅:

$(this).css('background','red').siblings().css('background','');

这样代码是不是优雅多了

Guess you like

Origin blog.csdn.net/qq_49900295/article/details/123830848