我有下面的代码按照需要工作但是on选项仅适用于第二次选择更改。
知道如何解决这个问题吗?
<html>
<head>
<title>select & select</title>
<script type='text/javascript'>
var select2data = {
'English': [['One', 1], ['Two', 2], ['Three', 3]],
'Spanish': [['Uno', 1], ['Dos', 2], ['Tres', 3]]
};
function change_second_select(){
var sel1 = document.getElementById('select1')
, sel2 = document.getElementById('select2');
sel1.onchange = function() {
var os = select2data[sel1.value]; // Get the options required by select1.
if (os) {
sel2.options.length = 0; // Clear the options for select2.
for (var i=0; i<os.length; i++) {
var o = new Option(os[i][0], os[i][1]);
try { // Add each option, allowing for browser differences.
sel2.add(o);
} catch (ex) {
sel2.add(o, null);
}
}
sel2.selectedIndex = 0;
}
return true;
};
}
</script>
<select id="select1" onchange="change_second_select();">
<option value="English">English</option>
<option value="Spanish">Spanish</option>
</select>
<select id="select2">
</select>
</head>
</html>
答案 0 :(得分:2)
将change_on_select更改为:
工作示例@ http://jsfiddle.net/3dCyw/1/
function change_second_select(){
var sel1 = document.getElementById('select1')
, sel2 = document.getElementById('select2');
var os = select2data[sel1.value]; // Get the options required by select1.
if (os) {
sel2.options.length = 0; // Clear the options for select2.
for (var i=0; i<os.length; i++) {
var o = new Option(os[i][0], os[i][1]);
try { // Add each option, allowing for browser differences.
sel2.add(o);
} catch (ex) {
sel2.add(o, null);
}
}
sel2.selectedIndex = 0;
}
return true;
}
答案 1 :(得分:1)
这也适用(jquery)
var select2data = {
'English': [['One', 1], ['Two', 2], ['Three', 3]],
'Spanish': [['Uno', 1], ['Dos', 2], ['Tres', 3]]
};
$(document).ready(function() {
$("#select1").bind("change", function() {
sel2 = $("#select2").get(0);
var os = select2data[this.value];
if (os) {
sel2.options.length = 0; // Clear the options for select2.
for (var i=0; i<os.length; i++) {
var o = new Option(os[i][0], os[i][1]);
try {
// Add each option, allowing for browser differences.
sel2.add(o);
}
catch (ex) {
sel2.add(o, null);
}
}
sel2.selectedIndex = 0;
}
return true;
});
});
</script>
<select id="select1">
<option value="English">English</option>
<option value="Spanish">Spanish</option>
</select>
<select id="select2">
答案 2 :(得分:1)
同意Cybernate。
sel1.onchange = function() {...}
这意味着您将事件附加到元素,但不执行它。