繁体   English   中英

如何使用 jquery 将字符串内的数字加一

[英]How can I increase a number that is inside a string by one using jquery

我正在使用一个 jquery 插件来创建选项卡以进行导航,除了最后一个硬编码的选项卡之外,所有选项卡都是动态加载的。 我仍然想像往常一样导航,以便标签需要在 +1 之前具有标签的 id。

这些是使选项卡工作的两个元素:

<a href="#step-10" class="nav-link">Vul je keuze aan</a>
<div id="step-10" class="" style="">

比如说上面的例子有 10 个步骤/选项卡,那么硬编码的步骤需要有:

<a href="#step-11" class="nav-link">Vul je keuze aan</a>
<div id="step-11" class="" style="">

我怎样才能做到这一点? 我不能只是将它解析为一个数字并加一,因为该数字与step-一起位于字符串中。 如何从该字符串中删除数字,增加它并将新数字放回去?

回答这个问题。 How can I remove the number from that string, increase it and put the new number back? 假设我将 id 分配给了一个 var

var id = "step-11"
var splittedId = id.split("-");    //["step", "11"]
var no = parseInt(splittedId[1]);  // 11
var step = splittedId[0];          // "step"
var newId = step+"-"+(++splittedId[1]); // "step-12"

您可以做的一件事是将所有带有 id 的 div 像step- count 一样,然后将这个 count +1 像下面的代码一样

 const test = document.querySelectorAll("div[id*='step-']");
 document.getElementsByClassName('testclass')[0].id='step-'+(test.length+1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM