[英]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.