我编写了代码来覆盖<select multiple="multiple">
. 我的结论是尝试这样做是个坏主意,因为每个浏览器如何处理输入和 jQuery 代码。
我建议 Mortensen 先生找到一个 UI 小部件或替代品,例如滚动 div 内的复选框,这将提供更可预测的行为,然后将我的代码功能应用于该选择。<select>
我坚持使用通用代码有多种选择:
不一致之处:我很惊讶Opera能按我的意愿工作。IE 7只是忽略了我的代码。Chrome:当按下一个键来选择一个不可见的项目时,它会向上滚动,但不会向下滚动。令人费解。Firefox:我不能event.preventDefault()
工作。所以我的整个代码都被忽略了。
http://jsfiddle.net/rtLF2/
<html>
<head>
<style type="text/css">
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var indices = {};
var count = 1;
// build a dictionary matching first letters to indices of where
// they were found
$("#mylist option").each(function() {
var letter = $(this).text().charAt(0).toLowerCase();
if(!indices[letter]) {
indices[letter] = [];
}
indices[letter].push(count);
count++;
});
var lastletter = "";
var lastindex = -1;
$("#mylist").on('keypress', function(event) {
event.preventDefault();
var pressed = String.fromCharCode(event.keyCode).toLowerCase();
if(pressed == lastletter) {
lastindex == indices[lastletter].length - 1 ? lastindex = 0 : lastindex++;
}
else {
lastletter = pressed;
lastindex = 0;
}
if(indices[lastletter]) {
var target = indices[lastletter][lastindex];
$("#mylist option:selected").each(function() {
$(this).removeAttr("selected");
});
$("#mylist option:nth-child(" + target + ")").attr("selected", "selected");
}
});
});
</script>
</head>
<body>
<select id="mylist" multiple="multiple" size="5">
<option value="1">Tank</option>
<option value="2">APC</option>
<option>Mini tricycle</option>
<option>Bike</option>
<option>Megatank</option>
<option>Brawler</option>
<option>Trailer</option>
<option>Md Tank</option>
<option>Armored van</option>
<option>War Machine</option>
</select>
</body>
</html>