2011-01-26 46 views
0

我想創建一個函數下面的代碼,將重複可變次數在1組合2個變量調用一個ID

myId##.className = myId##.className.replace(' class1',' class2') 

到目前爲止,我想出了以下,但它不工作。

function toggle(partId,orig,rep,itr) 
{ 
var partId; // Begining of Id string 
var orig; // Original Class 
var rep; // Replacement Class 
var itr; // Total number to be iterated through 
var num = 1; // Starting at 1 
var finalId; // for partId + num 
while (num<=itr) 
{ 
finalId = partId + num; 
finalId.className = finalId.className.replace(orig,rep); 
num++; 
} 
} 

然後我就這樣來實現它。

<area shape="circle" coords="933,92,23" 
     alt="myAlt" href="#none" 
     onmouseover="toggle('myPartId',' class1',' class2',5)" 
     onmouseout="toggle('myPartId',' class1',' class2',5)" /> 

所以我想我可以補充的ID節點className和我醚做錯了或者我是錯的,因爲它不能這樣做。

任何幫助將不勝感激。

+0

這還不清楚。第二個片段使用chang(),但最後一個片段調用toggle()?如果輸入和輸出工作正常,你期望什麼? – Merijn 2011-01-26 10:06:51

回答

1

與此

var el; 
while (num<=itr) 
{ 
finalId = partId + num; 
el = document.getElementById(finalId); 
el.className = el.className.replace(orig,rep); 
num++; 
} 
} 

改變你的while循環,並調用chang方法,而不是toggle ..(除非它是這裏的示例的故障..

0

你永遠不會得到ID指向的對象。 添加getElementById並嘗試。

{ 
finalId = partId + num; 
var element = document.getElementById(finalId); 
element.className = element.className.replace(orig,rep); 
num++; 
}