将索引附加到 href
我有一个无序列表的链接,我需要将索引作为数字附加到其中。
所以 href="#"
读取 href="#1"
、href="#2"
等。
我知道我可能需要使用.each()
但我的语法还没有达到标准。
我的一部分知道这非常简单,但我周一有一台自动取款机。
I have an unordered list of links that I need to append the index as a number to.
So href="#"
reads href="#1"
, href="#2"
etc.
I understand I probably need to use .each()
but my syntax-fu isn't up to scratch yet.
Part of me knows this is ridiculously simple but I'm having a monday atm.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的意思是所选元素集中元素的索引吗?如果是这样,您可以使用
.attr()
并向其传递一个函数:当然,您必须只选择您想要的链接,例如,通过为您的列表提供 ID:
更新:
jQuery 1.3 中似乎有一个错误.2(及之前)。 似乎旧值没有传递给回调< /a>.因此,您必须显式读取该值:
当然,如果旧值始终为
#
那么您可以将其与索引连接起来:但在这种情况下,您可以使用
each()
在这种情况下,如 @Shadow Wizard 在他的答案中显示 。将函数传递给 attr 的优点只是避免了对属性的两次访问(一次读取,一次写入),无论如何,这在 jQuery 1.3.2 中似乎不起作用。Do you mean the index of the element in the set of selected elements? If so you can use
.attr()
and pass a function to it:Of course you have to select only those links you want, e.g. by giving your list an ID:
Update:
There seems to be a bug in jQuery 1.3.2 (and before). It seems the old value is not passed to the callback. So you would have to read the value explicitly:
Of course if the old value is always
#
then you can just concatenate it with the index:But in this case, you could use
each()
in this case, as @Shadow Wizard shows in his answer. The advantage of passing a function toattr
is only that you avoid two access to the attribute (one to read and one to write), which does not seems to work in jQuery 1.3.2 anyway.好吧,今天是周日,但是..
实时测试用例。
Well, it's Sunday but..
Live test case.
更容易使用 .attr() 函数。
如果您仅限于 v1.1 之前的旧版 jQuery 实现,那么您将需要使用 .each():
Easier to use the .attr() function.
If you are restricted to older jQuery implementations older than v1.1, then you will need to use .each():