Here is my code:
<script language="javascript">
var counter =0,temp,m,cloneNodem;
function getVtierDefList(){
var vtierDefList = var vtierDefList = [{"label":"d1nis1w20","value":"28914"},{"label":"d1nis1m13","value":"28915"},{"label":"d1nis2d9","value":"28661"},{"label":"d1nis3d1","value":"28916"},{"label":"d1nis1a1","value":"27238"},{"label":"d1nis1a13","value":"28917"},{"label":"s2nis1d0","value":"28660"},{"label":"s2nis1a0","value":"28659"},{"label":"t3nis1d0","value":"27237"}];;
return vtierDefList;
}
</script>
</head>
<body onload="load();">
<div id="doc">
<div id="main">
<table id="vtier#1">
<tr>
<td><button onclick="delVtier(this);return false;" /></td>
<td>1.Vtier Name: <select id="vtier" name="vtierSelect" onchange="doAjax(this);return false;">
<option selected="selected" value="-1">Any</option>
</select></td>
</tr>
</table>
<div id="accountarea" >
</div>
</div>
</div>
<div id="plus"><button onclick="addVtier();return false;"/></div>
</body>
</html>
<script language="javascript">
function addVtier() {
m = document.getElementById("main");
cloneNodem = m.cloneNode(true);
temp = cloneNodem.cloneNode(true);
document.getElementById("main").appendChild(temp);
counter++;
fillDropDown(counter);
}
function load() {
var vtierSelectedList = document.getElementsByName("vtierSelect");
addDropDownValues(getVtierDefList(), vtierSelectedList[0],"-1");
}
function addDropDownValues(Elements,DropDwn,SelectID)
{ if(DropDwn.options){
DropDwn.options.length = 1
}
for(var i=0;i<Elements.length;i++)
{
var addOption = new Option();
addOption.value = Elements[i].value;
addOption.innerHTML = Elements[i].label;
if(addOption.value == SelectID)addOption.selected = true;
DropDwn.appendChild(addOption);
}
}
function fillDropDown(dropDwn) {
var vtierSelectedList = document.getElementsByName("vtierSelect");
vtierSelectedArray = new Array(vtierSelectedList.length);
var vtierDefList = getVtierDefList();
for(var k=0;k<vtierSelectedList.length;k++) {
vtierSelectedArray[k] =vtierSelectedList[k].options[vtierSelectedList[k].selectedIndex].value ;
}
var diff = diffArray(getVtierDefList(), vtierSelectedArray);
addDropDownValues(diff,vtierSelectedList[dropDwn],"-1");
}
// this function diffArray just finds the difference between the two arrays
function diffArray(a, b) {
var seen = [], diff = [];
for ( var i = 0; i < b.length; i++)
seen[b[i]] = true;
for ( var i = 0; i < a.length; i++)
if (!seen[a[i].value])
diff.push(a[i]);
return diff;
}
</script>
现在我的问题是,当此代码填充第一个下拉列表的下拉列表时,为什么它不会填充下一个下拉列表的下拉列表,新的计算数组没有在下拉框中已经选择的元素?
答案 0 :(得分:1)
一个可能的问题是你如何为你的选择添加选项。而不是:
DropDwn.appendChild(addOption);
选择此选项:
DropDwn.options.add(new Option(Elements[i].label, Elements[i].value));
你的选择有一个id,所以而不是
var vtierSelectedList = document.getElementsByName("vtierSelect");
addDropDownValues(getVtierDefList(), vtierSelectedList[0],"-1");
只需按id:
选择此元素即可var vtierSelectedList = document.getElementsById("vtier");
addDropDownValues(getVtierDefList(), vtierSelectedList,"-1");