首页 前端知识 jQuery——37. 获取元素索引及元素遍历【 index( ), each( ) 】

jQuery——37. 获取元素索引及元素遍历【 index( ), each( ) 】

2025-03-23 11:03:19 前端知识 前端哥 23 993 我要收藏

1.index() 方法返回指定元素的索引位置。
如果未找到元素,index() 将返回 -1
$(this).index()获取当前操作元素的索引值

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
span{
display: block;width: 200px;line-height: 30px;text-align: center;
margin-top:20px ;background: #ccc;
}
button{
width: 200px;height: 50px;margin-top:50px ;
}
</style>
<script src="../js/jquery-3.4.1.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function(){
//1.index() 方法返回指定元素的索引位置。
//如果未找到元素,index() 将返回 -1
// $(this).index()获取当前操作元素的索引值
$("#box span").click(function(){
var index = $(this).index();
alert(index);
});
})
</script>
</head>
<body>
<div id="box">
<span>51zxw</span>
<span>51zxw</span>
<span>51zxw</span>
<span>51zxw</span>
<span>51zxw</span>
<span>51zxw</span>
</div>
<button>按钮</button>
</body>
</html>
复制

在这里插入图片描述

2. each( ) 方法规定为每个匹配元素规定运行的函数。就是对元素遍历(做循环)
each()函数可以接收正在遍历元素的索引

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
span{
display: block;width: 200px;line-height: 30px;text-align: center;
margin-top:20px ;background: #ccc;
}
button{
width: 200px;height: 50px;margin-top:50px ;
}
</style>
<script src="../js/jquery-3.4.1.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function(){
//2.each() 方法规定为每个匹配元素规定运行的函数。就是对元素遍历(做循环)
//each()函数可以接收正在遍历元素的索引如遍历一个传一个索引
$("button").click(function(){
$("#box span").each(function(i){//each给获取的span元素集合做遍历
//$(this).text("我要自学网");
$(this).text("我要自学网"+i);
$(this).attr("id","zxw"+i);//通过遍历给元素添加属性,及属性值
});
});
})
</script>
</head>
<body>
<div id="box">
<span>51zxw</span>
<span>51zxw</span>
<span>51zxw</span>
<span>51zxw</span>
<span>51zxw</span>
<span>51zxw</span>
</div>
<button>按钮</button>
</body>
</html>
复制

在这里插入图片描述
在这里插入图片描述

转载请注明出处或者链接地址:https://www.qianduange.cn//article/24269.html
标签
评论
发布的文章

【Linux笔记】基础IO(上)

2025-03-27 13:03:40

大家推荐的文章
会员中心 联系我 留言建议 回顶部
浏览器升级提示:您的浏览器版本较低,建议您立即升级为知了极速浏览器,极速、安全、简约,上网速度更快!立即下载
复制成功!