Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个包含多个 div 的页面,我想在每个 div 中添加一个递增的数字。
我认为这可以完成这项工作,但事实并非如此:
$(document).ready(function(){ var i; while ( i<count) { $('#div').append(i); i++; } });
我在之后添加了这个脚本</body>
</body>
$(function(){ $('div').slice(0, count).each(function(i){ $(this).append(i+1); }); });
.slice()用于选择前 n 个匹配的元素(如 建议的那样)i < count。有关更多信息,请参阅此帖子。
.slice()
i < count
演示在这里
此外..
如果您的 div(或任何元素)是彼此的兄弟,您可以使用更优雅的..
$('mySelector').each(function(){ $(this).append($(this).index()) });
这是一种方法:
$("div").each(function(i){ $(this).append(i); });
演示