我在这个问题上完全矫枉过正:) 有趣的问题,希望它能教给你一些东西。
参见 JSFiddle
HTML
<div>
<label for="chars">Chars:</label>
<input id="chars" type="text" />
</div>
<div>
<input id="names" type="radio" name="names-radio" checked />
<label for="names">Names</label>
<input id="animals" type="radio" name="names-radio" />
<label for="animals">Animals</label>
</div>
<button id="get-names">Get values!</button>
<div>
<span>Result</span>
<div id="result"></div>
</div>
JavaScript
document.getElementById('get-names').onclick = getNamesClick;
function getNamesClick() {
var chars = document.getElementById('chars').value;
var names = document.getElementById('names').checked ? 'names' :
document.getElementById('animals').checked ? 'animals' : ''
var result = getNamesByChars(chars, names);
alert(result);
console.log(document.getElementById('result'));
document.getElementById('result').innerHTML = result;
}
function getNamesByChars(chars, names) {
var result = '';
charsArray = chars.split(' ');
for (var i = 0; i < charsArray.length; i++) {
var values = data[names][charsArray[i]];
for (var j = 0; j < values.length; j++) {
if (result != '')
result += ' ';
result += values[j];
}
}
return result;
}
var data = {
'names': {
'a': [ 'Andrew', 'Allison' ],
'b': [ 'Bob', 'Barry' ],
'c': [ 'Cheryl', 'Carol' ],
'd': [ 'Daniel', 'Danny' ],
'e': [ 'Eddie', 'Emma' ],
'f': [ 'Frank', 'Flo' ],
'g': [ 'Greg', 'Grant' ],
'h': [ 'Holly' ],
'i': [ 'Ian' ],
'j': [ 'John' ],
'k': [ 'Kaylie' ],
'l': [ 'Liam' ],
'm': [ 'Mary' ],
'n': [ 'Ned' ],
'o': [ 'Oliver' ],
'p': [ 'Peter' ],
'q': [ 'Quentin' ],
'r': [ 'Ryan' ],
's': [ 'Sarah' ],
't': [ 'Tom' ],
'u': [ 'Ualani' ],
'v': [ 'Victor' ],
'w': [ 'Will' ],
'x': [ 'Xan' ],
'y': [ 'Yvette' ],
'z': [ 'Zoe' ]
},
'animals': {
'd': [ 'Dog', 'Dolphin' ],
'e': [ 'Elephant' ]
}
}