jQuery----each()方法

时间:2024-10-15 19:35:02

jquery中有隐式迭代,不需要我们再次对某些元素进行操作。但是如果涉及到不同元素有不同操作,需要进行each遍历。本文利用10个li设置不同的透明度的案例,对each方法进行说明。

语法:

$(元素).each(function(index,element){ });

参数index:表示元素索引,在本例中是0-9

参数element:表示对象,在本例中是每个li

案例效果:

jQuery----each()方法

代码如下

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
li{
width: 100px;
height: 100px;
background-color: green;
list-style: none;
float: left;
margin-left: 10px;
}
</style> <script src="jquery-1.12.2.js"></script>
<script type="text/javascript">
$(function(){
//页面加载后,让每个li的透明度发生改变
$("li").each(function(index,element){
//第一个参数是索引,第二个参数是对象
$(element).css("opacity",(index+1)/10);
})
});
</script>
</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>