欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

jQuery的基本工作原理

程序员文章站 2022-04-08 08:46:11
...
一次性获取多个元素,然后循环进行处理,这样的操作在js中非常普遍,为了简化这类操作,jQuery横空出世,

下面我们用jQuery来快速改写一下,体验一下jQuery带来了的,前所未有的酸爽感觉

首先我们要导入一个jQuery,这里我先用cdn快速导入jquery函数库,演示一下

<!-- 第一步: 导入jquery库 -->

<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js

"></script>

<!-- 第二步: 写jquery代码 -->

<script type="text/javascript">

$('li:nth-child(4) ~ *').css({'background-color':'orangered','color':'white'})

</script>

//同时处理多个元素,你会发现只有第5个背景发生变化,这是为什么呢?

//尽管选择器li:nth-child(4)~*选择了多个元素,但是querySelector()中会返回一个,所以只返回了符合条件的第一个元素

// document.querySelector('li:nth-child(4) ~ *').style.backgroundColor = 'lightgreen'

//如何才能获取到所有符合选择器条件的元素呢?需要使用querySelectorAll()方法

//因为返回的是一个元素集合(数组),我们需要用循环来完成这个操作

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>

以上就是jQuery的基本工作原理的详细内容,更多请关注其它相关文章!