Obtain multiple elements at one time and then process them in a loop. This kind of operation is very common in js. In order to simplify this kind of operation, jQuery was born.
Let’s use jQuery to quickly rewrite it. Experience the unprecedented sour feeling brought by jQuery
First we need to import a jQuery. Here I will use cdn to quickly import the jquery function library and demonstrate it
$('li:nth-child(4) ~ *').css({'background-color':'orangered','color':'white'} )
//When processing multiple elements at the same time, you will find that only the fifth background changes. Why is this?
// Although the selector li:nth-child(4)~* selects multiple elements, querySelector() will return one, so only the first element that meets the conditions is returned
// document.querySelector ('li:nth-child(4) ~ *').style.backgroundColor = 'lightgreen'
//How to get all elements that meet the selector conditions? You need to use the querySelectorAll() method
//Because what is returned is a collection of elements (array), we need to use a loop to complete this operation
var balls = document.querySelectorAll('li:nth-child(4) ~ *') alert(balls.length) for (var i=0; i<balls.length; i++) { balls[i].style.backgroundColor = 'lightgreen' }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>1.jQuery的基本工作原理</title> <style type="text/css"> ul { margin:30px; padding:10px; overflow: hidden; } li { list-style-type: none; width: 40px; height: 40px; margin-left:10px; background-color: lightskyblue; text-align: center; line-height: 40px; font-size: 1.2em; font-weight: bolder; float:left; border-radius: 50%; box-shadow: 2px 2px 2px #808080; } /*将第一个li背景换成绿色*/ li:first-child { /*background-color: lightgreen;*/ } /*再将第4个元素背景换成橙色,前景换成白色*/ li:nth-child(4) { /*background-color: orangered;*/ /*color: white;*/ } li:nth-child(4) ~ * { /*background-color: lightgreen;*/ } </style> </head> <body> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li>10</li> </ul> </body> </html>
The above is the detailed content of How jQuery basically works. For more information, please follow other related articles on the PHP Chinese website!