CSS计数器的jQuery/Javascript等效方法?

4

是否可以使用jQuery/Javascript直接更改标签文本的计数器?例如,如果我有2个标签:

<a>hello</a>
<a>bye</a>

运行jQuery/JS函数后,以下是可能发生的情况:
<a>[1]hello</a>
<a>[2]bye</a>

我无法使用CSS计数器,因为我需要脚本直接编辑HTML。


对于每一个元素,设置文本,然后递增数字。 - Seano666
所以选择元素,循环并添加文本吗? - epascarello
4个回答

5
你可以使用.html(function)

$("a").html(function(index, html) {
  return "[" + (index + 1) + "]" + html;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<a>hello</a>
<a>bye</a>


1
使用纯JS,您可以创建一个文本节点并将其作为第一个子节点插入以获取计数器 - 请参见下面的演示:

Array.prototype.forEach.call(document.querySelectorAll("a"), function(e, i) {
  e.insertBefore(document.createTextNode(`[${i+1}]`), e.childNodes[0]);
});
<a>hello</a>
<a>bye</a>


1
你可以循环遍历所有锚点,使用 .prepend() 将索引添加到内容中:
$("a").each(function(index,value) {
    $(this).prepend("["+(index++)+"] ");
})

希望这可以帮到您。

$("a").each(function(index,value) {
   $(this).prepend("["+(index++)+"] ");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<a>hello</a>
<a>bye</a>


为什么需要.each()? .html()迭代jQuery对象的所有元素。 - guest271314
这是对于 OP 问题的另一种解决方案 :) - Zakaria Acharki

1
使用此代码,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<a>hello</a>
<a>bye</a>

<script>
$("a").html(function(index, data) {
  return "[" + (index + 1) + "]" + data;
})
</script>

1
javascript 在 Answer 中与 https://dev59.com/Op3ha4cB1Zd3GeqPZMBU#41384631/? 中的 javascript 有何不同? - guest271314
@user7354735 请不要重复回答。 - Zakaria Acharki
这不是重复的答案,我只是指出适合放置jQuery函数的位置。 - user7354735
不要和我争吵,这只是一个简单而常见的脚本,不能用多种方式编写。 - user7354735
1
html 更改为 data 会有什么不同呢? - Zakaria Acharki
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接