Kha*_*ine 0 javascript drop-down-menu
我有一个项目列表:
<select id ="listSelector">
<option value="books">Books</option>
<option value="countries">Countries</option>
<option value="states">States</option>
<option value="presidents">Presidents</option>
</select>
Run Code Online (Sandbox Code Playgroud)
对应于项目数组:
var books = ['genesis', 'exodus', 'leviticus', 'numbers'];
var countries = ['Akrotiri','Albania','Algeria','American'];
var states = ['Alabama','Alaska','Arizona','Arkansas'];
var presidents = ['Washington','Adams','Jefferson','Madison'];
Run Code Online (Sandbox Code Playgroud)
我希望能够从列表中选择一个项目并使用该项目的值来选择正确的数组.
var listSelector = document.getElementById('listSelector');
var selectedList = listSelector.options[listSelector.selectedIndex].value;
console.log('selected', selectedList[0]);
// returns first letter of the value of the list that was selected
// instead of the first item in the array.
// Ex. If I selected the Books option, the value would be 'books'
// and I want to access the books array.
Run Code Online (Sandbox Code Playgroud)
如果您将结构更改为对象,那将非常简单
var stuff = {
books : ['genesis', 'exodus', 'leviticus', 'numbers'],
countries : ['Akrotiri', 'Albania', 'Algeria', 'American'],
states : ['Alabama', 'Alaska', 'Arizona', 'Arkansas'],
presidents : ['Washington', 'Adams', 'Jefferson', 'Madison']
}
var listSelector = document.getElementById('listSelector');
listSelector.addEventListener('change', function() {
var item_array = stuff[listSelector.value];
document.getElementById('result').innerHTML = '<pre>' + JSON.stringify(item_array, 0, 4) + '</pre>';
}, false);Run Code Online (Sandbox Code Playgroud)
<select id="listSelector">
<option value="books">Books</option>
<option value="countries">Countries</option>
<option value="states">States</option>
<option value="presidents">Presidents</option>
</select>
<div id="result"></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27 次 |
| 最近记录: |