2017-03-01 62 views
-1

讓我們假設我得到了一些數組的王...或者爲了簡單的鏈接。JS - 遍歷數組併爲if語句添加新數字

HTML:

<a href'myspecialPath'></a> 
<a href'myspecialPath'></a> 
<a href'otherPath'></a> 
<a href'otherPath'></a> 
<a href'myspecialPath'></a> 
<a href'myspecialPath'></a> 

JS:

var test = document.getElementsByTagName('a'); 
var testLength = test.length; 

for (i=0; i<testLength; i++){ 
    if (test.getAttribute('href').indexOf('myspecialPath') !== -1){ 
     //we list here every link with special patch 
     // and I want it to have new numeration, not: 
     link[i] have myspecialPath! // 1,2,5,6 
     // cause it has gaps if link don't have special path - 1,2,5,6 
     // and I want it to have numeric like 1,2,3,4 
    } 
else{ 
     link[i] without myspecialPath! // 3,4... and I want 1,2 
    } 
} 

我希望一切都清楚了。我想從1 [i + 1]到下一個數字鏈接,沒有間隙。

編輯: 我也嘗試[Y + 1]之前,但由於@American煤泥答案是:

y = 0; 
for (i=0; i<testLength; i++){ 
     if (test.getAttribute('href').indexOf('myspecialPath') !== -1){ 
      links:[y ++] have myspecialPath! // 1,2,3,4... and so on, OK - it's working fine! 
     } 
    } 

有人下跌自由來糾正這個問題/答案,以便更好地說明問題。

+1

仍然模糊!解釋更多! –

+0

不要使用'link [i]',而是使用'link.push(item)'? – sweaver2112

+0

創建一個計數器變量,並且只在「if」命中時增加它。請使用計數器變量而不是i – Aaron

回答

1

我敢肯定這是你在問什麼......

var links = document.querySelectorAll('a'); 
var count = 1; 

for (var i = 0; i <= links.length-1; i++) { 

    if (links[i].getAttribute('href') === 'myspecialPath') { 

     links[i].setAttribute('href', 'myspecialPath' + count); 
     count++; 

    }; 

}; 
+0

我認爲它很接近,我只是想收集適當的迭代,但不是[我]數字,我想我自己從1到...(沒有洞/缺口像1,2,[缺少3,4這裏不是所有原因鏈接履行if語句] 5,6) – webmasternewbie

+0

@webmasternewbie目前還不清楚你在問什麼。你能顯示你想要的列表是什麼樣子嗎? – Slime

+0

我編輯了我的問題...只需增加...你學會了你所有的生活:) – webmasternewbie

1

我想,你希望是什麼myspecialPath鏈接和其他等環節組成的數組。您可以使用Array.prototype.push,它不關心像這樣的索引:

var test = document.getElementsByTagName('a'); 
var testLength = test.length; 

var specialLinks = []; 
var otherLinks = []; 

for (i=0; i<testLength; i++){ 
    // it should be test[i] not test 
    if (test[i].indexOf('myspecialPath') !== -1){ 
     specialLinks.push(test[i]); 
    } 
    else{ 
     otherLinks.push(test[i]); 
    } 
} 
+0

非常好,對於數組! – webmasternewbie