2017-03-01 41 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