2014-05-23 52 views
0

我有wriiten javascriot兩級下拉選擇值在第一我得到值在第二下拉。現在發生了什麼,數組中的值被分配到第二個下拉列表中。我想分配urls作爲第二個下拉列表的值,並將它們重定向到下拉列表。在下面的示例中,如果我選擇了服裝,那麼我在第二個下拉列表中選擇男士和女士,因此如果我選擇第二個下拉列表中的男士,它應該轉到xyz.com ....所以在第二個下拉列表中的每個選項,我希望它被重定向到一個特定的網址,我該怎麼做?使用javascript將值分配給下拉菜單

<html> 
<head> 

<script type="text/javascript"> 

var categories = [];categories["startList"] = ["Apparel","Books"] 
categories["Apparel"] = ["Men","Women"]; 
categories["Books"] = ["Biography","Fiction","Nonfiction"]; 


var nLists = 2; // number of lists in the set 

function fillSelect(currCat,currList){ 
var step = Number(currList.name.replace(/\D/g,"")); 
for (i=step; i<nLists+1; i++) { 
document.forms[0]['List'+i].length = 1; 
document.forms[0]['List'+i].selectedIndex = 0; 
} 
var nCat = categories[currCat]; 
//var nurl= url[currCat] 
for (each in nCat) { 
var nOption = document.createElement('option'); 
var nData = document.createTextNode(nCat[each]); 
nOption.setAttribute('value',nCat[each]); 
nOption.appendChild(nData); 
currList.appendChild(nOption); 
} 
} 

function getValue(isValue) { 
alert(isValue); 
} 

function init() { 
fillSelect('startList',document.forms[0]['List1']) 
} 

navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);  

</script> 
</head> 

<body> 
<form action=""> 
<select name='List1' onchange="fillSelect(this.value,this.form['List2'])"> 
<option selected>Make a selection</option> 
</select> 
&nbsp; 
<!--<select name='List2' onchange="fillSelect(this.value,this.form['List3'])"> 
<option selected>Make a selection</option> 
</select>--> 
&nbsp; 
<select name='List2' onchange="getValue(this.value)"> 
<option selected >Make a selection</option> 
</select> 
</form> 

</body> 
</html> 
+0

你的意思是你想用數組數據填充'dropdown'嗎? – jhyap

+0

是與網址數組數據 – user818671

回答

0

首先,你需要修改源數組作爲JSON格式是這樣的:現在

var categories = [];categories["startList"] = [{"text":"Apparel","url":"Apparel"},{"text":"Books","url":"Books"}] 
categories["Apparel"] = [{"text":"Men","url":"xyz.com"},{"text":"Women","url":"abc.com"}]; 
categories["Books"] = [{"text":"Biography","url":"Biography.com"},{"text":"Fiction","url":"Fiction.com"},{"text":"Nonfiction","url":"Nonfiction.com"}]; 

,在功能上,我們可以用它作爲鍵值對:

var nLists = 2; // number of lists in the set 

function fillSelect(currCat,currList){ 
var step = Number(currList.name.replace(/\D/g,"")); 
for (i=step; i<nLists+1; i++) { 
document.forms[0]['List'+i].length = 1; 
document.forms[0]['List'+i].selectedIndex = 0; 
} 
var nCat = categories[currCat]; 
//var nurl= url[currCat] 
for (each in nCat) { 
var nOption = document.createElement('option'); 
var nData = document.createTextNode(nCat[each]["text"]); 
nOption.setAttribute('value',nCat[each]["url"]); 
nOption.appendChild(nData); 
currList.appendChild(nOption); 
} 
} 

function getValue(isValue) { 
//alert(isValue); 
location.replace("http://" + isValue); 
} 

這就是它!