简体   繁体   中英

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. I still want to navigate like usual so that tab needs to have the id of the tab before it +1.

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:

<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- . 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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