Jquery - 如何设置索引从1开始而不是0的属性?

1 indexing jquery attributes

$('ul li a').each(function(index, element){$(element).attr("href", "#img"+index);});
Run Code Online (Sandbox Code Playgroud)

我希望我的列表项链接以href开头为"#img1",并从那里为每个项目计数.我的代码将从"#img0"开始,这对我想要完成的工作不起作用.

谢谢你的帮助.

Nic*_*ver 5

从jQuery 1.4+开始,.attr()直接获取一个函数,如下所示:

$('ul li a').attr("href", function(index) { return "#img" + (index+1); });
Run Code Online (Sandbox Code Playgroud)

索引仍然基于0,因此在使用时只需添加1.