我想将 div 背景颜色更改为绿色 onmouseover 事件,但我不确定为什么我不断收到此错误 TypeError: Cannot read property 'style' of undefined
这是我的 JS 代码:
// JavaScript 文档
s1= new String()
var myArray = new Array();
var div_id=0;
myArray[0] = "Donald Duck";
myArray[1] = "Winnie Pooh";
myArray[2] = "Komal Waseem";
myArray[3] = "Hockey";
myArray[4] = "Basketball";
myArray[5] = "Shooting";
myArray[6] = "Mickey Mouse";
function test(){
s1 = document.getElementById('filter').value;
var myRegex = new RegExp((s1),"ig");
arraysearch(myRegex);
}
function arraysearch(myRegex){
var flag=0;
for(b=1; b<=div_id; b++)
{
var d = document.getElementById('lc');
var olddiv= document.getElementById("div" + b);
if(olddiv){
d.removeChild(olddiv);}
}
for(i=0; i<myArray.length; i++)
{
if (myArray[i].match(myRegex)){
div_id++;
flag=1;
document.getElementById('lc').style.visibility='visible';
var element = document.createElement("div");
element.setAttribute('id', "div" + div_id);
element.appendChild(document.createTextNode(myArray[i]));
document.getElementById('lc').appendChild(element);
var x =document.getElementsByTagName("div")
for(t=0; t<x.length; t++)
{
//alert(t);
if(x[t]){
x[t].onmouseover = function(){
x[t].style.backgroundColor='green';
}
}
}
}
if (flag ==0){
document.getElementById('lc').style.visibility='hidden'; }
}
}