$(selector).each(function(index, element))
index: 是一个整数值,用于指定选择器的索引位置。
element: 是当前元素。我们可以使用此关键字来引用当前匹配的元素。
<!DOCTYPE html>
<html>
<head>
<title> jQuery each() method </title>
<script src="/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h2> Welcome to the bianchenghao6.com </h2>
<ul>
<li> First element </li>
<li> Second element </li>
<li> Third element </li>
<li> Fourth element </li>
</ul>
<p>
Click the following button to see the list of <b> li </b> elements.
</p>
<button onclick = fun()> Click me </button>
<script>
function fun(){
$(document).ready(function(){
$("li").each(function(){
alert($(this).text())
});
});
}
</script>
</body>
</html>
Welcome to the bianchenghao6.com
Click the following button to see the list of li elements.
<!DOCTYPE html>
<html>
<head>
<title> jQuery each() method </title>
<script src="/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
body{
text-align: center;
}
ul{
list-style-type: none;
float: left;
}
li {
width: 40px;
height: 40px;
margin: 5px;
padding: 5px;
font-size: 20px;
float: left;
border: 2px solid blue;
}
button{
font-size: 20px;
}
</style>
</head>
<body>
<h2> Welcome to the bianchenghao6.com </h2>
<ul>
<li> 1 </li>
<li> 2 </li>
<li> 3 </li>
<li id = "i4"> Stop </li>
<li> 5 </li>
<li> 6 </li>
</ul>
<button onclick = "fun()"> Click me </button>
<p></p>
<script>
function fun() {
$(document).ready(function(){
$("li").each(function(index, element) {
$(element).css("background", "lightgreen");
if ($(this).is("#i4")) {
$("p").text("Index begins with 0. So, the function stopped at position: " + index ).css("fontSize", "20px");
return false;
}
});
});
}
</script>
</body>
</html>