<script type="text/javascript">
window.onload = function () {
var box = document.getElementById('divselect'),
title = box.getElementsByTagName('cite')[0],
menu = box.getElementsByTagName('ul')[0],
as = box.getElementsByTagName('a'),
index = -1,
lis = menu.childNodes;
// 点击三角时
title.onclick = function (event) {
// 执行脚本
event = event || window.event;
if(event.stopPropagation){
event.stopPropagation();
}else{
event.cancelBubble = true;
}
menu.style.display = 'block';
}
for(var i=0;i<as.length;i++)
{
as[i].onmouseover = function () {
this.style.background = "#567";
}
as[i].onmouseout = function () {
this.style.background = '#fff';
}
as[i].onclick = function (e) {
e = e || window.event;
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
menu.style.display = "none";
title.innerHTML = this.innerHTML;
}
}
document.onkeydown = function (event) {
event = event || window.event;
if (event.keyCode == 38) {
index--;
if (index < 0) index = 0;
} else if (event.keyCode == 40) {
index++;
if (index > 4) index = 4;
}
for (var i = 0; i < as.length; i++) as[i].style.background = '#fff';
as[index].style.background = '#567';
if (event.keyCode == 13) {
if (index == -1) {
title.innerHTML = title.innerHTML;
menu.style.display = "block";
}
else {
title.innerHTML = as[index].innerHTML;
menu.style.display = "none";
}
}
}
document.onclick = function () {
menu.style.display = "none";
}
//document.onkeydown = function (event) {
// event = event || window.event;
// console.log(event.keyCode);
//}
}
</script>
我这个代码在没有任何选项被选中时,按下回车不做任何操作,但会报错“Uncaught TypeError: Cannot read property 'style' of undefined”
求解~
as[index].style.background = '#567';
根据你的代码,在没有点击上下键的情况下,index为初始值 -1 ,超过数组的临界值,所以报错