简体   繁体   English

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

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

I am using a jquery plugin that creates tabs to navigate through, all tabs are loaded dynamically except the last one which is hardcoded.我正在使用一个 jquery 插件来创建选项卡以进行导航,除了最后一个硬编码的选项卡之外,所有选项卡都是动态加载的。 I still want to navigate like usual so that tab needs to have the id of the tab before it +1.我仍然想像往常一样导航,以便标签需要在 +1 之前具有标签的 id。

These are the two elements that make the tabs work:这些是使选项卡工作的两个元素:

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

Say for example like above there are 10 steps/tabs, then the hardcoded step needs to have:比如说上面的例子有 10 个步骤/选项卡,那么硬编码的步骤需要有:

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

How can I do that?我怎样才能做到这一点? I can't just parse it as a number and increase by one since the number is inside a string alongside with step- .我不能只是将它解析为一个数字并加一,因为该数字与step-一起位于字符串中。 How can I remove the number from that string, increase it and put the new number back?如何从该字符串中删除数字,增加它并将新数字放回去?

Answer to this question.回答这个问题。 How can I remove the number from that string, increase it and put the new number back? Let's say I have the id assigned to a var假设我将 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"

A thing you can do is take all the divs with id like step- count them and put this count +1 like the code below您可以做的一件事是将所有带有 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