一次性获取多个元素,然后循环进行处理,这样的操作在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的基本工作原理的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号