Javascript根据另一个下拉框值更改下拉框选项 [英] Javascript change drop-down box options based on another drop-down box value
问题描述
我正在用 JavaScript 练习编程,我发现了一个问题,必须由一些专家回答有关 下拉
框的问题.
I am practising programming in JavaScript and I have found a problem that must be answered by some experts regarding drop-down
boxes.
场景是:
我有一个 drop-down
框,它提供了一些可能的省份选项,还有一个(城镇),它仅取决于在省份中选择的内容 drop-down代码>.
I have a drop-down
box that gives some possible options for provinces and also a second one (town) which depends only on what is selected in the provinces drop-down
.
JavaScript 中有没有办法让我在选择省份时,第二个 drop-down
给出所选省份的选项?
Is there a way in JavaScript that when I chose among provinces, the second drop-down
gives the options from the province selected?
推荐答案
这里有一个简单的例子来帮助你入门.
Here is a simple example to get you started.
它的工作原理是将 change
事件的事件侦听器附加到省下拉列表,然后通过 provs
对象查找该省的城镇.
It works by attaching an event listener for the change
event to the province dropdown, then looks up what towns are in that province via the provs
object.
有关每行功能的详细说明,请参阅注释.
See the comments for a detailed explanation of what each line does.
window.onload = function() {
// provs is an object but you can think of it as a lookup table
var provs = {
'British Columbia': ['Victoria', 'Sanitch'],
'Ontario': ['Bracebridge', 'Waterloo']
},
// just grab references to the two drop-downs
prov_select = document.querySelector('#prov'),
town_select = document.querySelector('#town');
// populate the provinces drop-down
setOptions(prov_select, Object.keys(provs));
// populate the town drop-down
setOptions(town_select, provs[prov_select.value]);
// attach a change event listener to the provinces drop-down
prov_select.addEventListener('change', function() {
// get the towns in the selected province
setOptions(town_select, provs[prov_select.value]);
});
function setOptions(dropDown, options) {
// clear out any existing values
dropDown.innerHTML = '';
// insert the new options into the drop-down
options.forEach(function(value) {
dropDown.innerHTML += '<option name="' + value + '">' + value + '</option>';
});
}
};
<select id="prov"></select>
<select id="town"></select>
这篇关于Javascript根据另一个下拉框值更改下拉框选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!