扫码关注官方订阅号
如上代码是我想要的结果,因为我不能确定span元素的数量,所以我想在js里面用for循环给它设置属性,但是循环完成后每个index-num属性的值都变成了length-1,代码如下。
var spans = $('.close'); for(var i=0; i
请问我应该怎么解决?
走同样的路,发现不同的人生
html
<span class="close"></span> <span class="close"></span> <span class="close"></span> <span class="close"></span>
js
$('.close').each(function (i) { $(this).attr('index-num', i); })
你的代码逻辑错了,spans.attr('index-num', i);这段代码是对所有的span.close进行操作了,所以你得到的结果是每个都是length-1. 你可以换成spans.eq(i).attr('index-num',i); 进行操作,或者使用回答中的其他人的答案。
spans.attr('index-num', i);
spans.eq(i).attr('index-num',i);
jquery中有个index方法可以确定元素所在位置
是在不知道题主要做什么
var spans = $('.close'); spans.each(function() { $(this).attr('index-num', $(this).index()) })
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
htmljs你的代码逻辑错了,
spans.attr('index-num', i);这段代码是对所有的span.close进行操作了,所以你得到的结果是每个都是length-1. 你可以换成
spans.eq(i).attr('index-num',i);进行操作,或者使用回答中的其他人的答案。jquery中有个index方法可以确定元素所在位置
是在不知道题主要做什么