我有一个动态链式选择框,我试图显示页面加载的值。在我的链式选择框中,它将默认为页面加载时选择框中的第一个选项,是否有人可以提供协助?
我偶然发现了这个帖子,但我似乎无法用我的CF语言翻译他们正在做的事情。 Dynamic chained drop downs on page refresh
这是我正在使用的JS脚本。
function dynamicSelect(id1, id2) {
// Feature test to see if there is enough W3C DOM support
if (document.getElementById && document.getElementsByTagName) {
// Obtain references to both select boxes
var sel1 = document.getElementById(id1);
var sel2 = document.getElementById(id2);
// Clone the dynamic select box
var clone = sel2.cloneNode(true);
// Obtain references to all cloned options
var clonedOptions = clone.getElementsByTagName("option");
// Onload init: call a generic function to display the related options in the dynamic select box
refreshDynamicSelectOptions(sel1, sel2, clonedOptions);
// Onchange of the main select box: call a generic function to display the related options in the dynamic select box
sel1.onchange = function() {
refreshDynamicSelectOptions(sel1, sel2, clonedOptions);
}
}
}
function refreshDynamicSelectOptions(sel1, sel2, clonedOptions) {
// Delete all options of the dynamic select box
while (sel2.options.length) {
sel2.remove(0);
}
// Create regular expression objects for "select" and the value of the selected option of the main select box as class names
var pattern1 = /( |^)(select)( |$)/;
var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
// Iterate through all cloned options
for (var i = 0; i < clonedOptions.length; i++) {
// If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box
if (clonedOptions[i].className.match(pattern1) || clonedOptions[i].className.match(pattern2)) {
// Clone the option from the hidden option pool and append it to the dynamic select box
sel2.appendChild(clonedOptions[i].cloneNode(true));
}
}
}
非常感谢您的帮助
答案 0 :(得分:1)
在调用dynamicSelect
之前,将原始选定的索引保存在refreshDynamicSelectOptions
函数中,如下所示:
var nOriginalSelection = sel2.selectedIndex;
将此传递给refreshDynamicSelectOptions
函数:
refreshDynamicSelectOptions(sel1, sel2, clonedOptions, nOriginalSelection);
添加到函数声明:
function refreshDynamicSelectOptions(sel1, sel2, clonedOptions, sel2Index) {
最后在该函数中,在追加所有匹配选项后添加此行:
sel2.selectedIndex = sel2Index;
答案 1 :(得分:0)
所以你遇到麻烦的是第二次下拉到第一个选项?
sel2.selectedIndex = 0;