让我们假设我得到了一些数组的王...或者为了简单的链接。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!
}
}
有人下跌自由来纠正这个问题/答案,以便更好地说明问题。
仍然模糊!解释更多! –
不要使用'link [i]',而是使用'link.push(item)'? – sweaver2112
创建一个计数器变量,并且只在“if”命中时增加它。请使用计数器变量而不是i – Aaron