0
object = ["a","input","textarea","select","img","#content",".view"];
for (var i = 0; i < oj.length; i++) {
    var resources = document.querySelector(object[i]);
    resources.addEventListener('mouseover', function(){alert("test");}, false);
}

错误TypeError: resources is null,如何解决?

4

2 回答 2

3

我猜对非虚假值(元素匹配选择器)的基本检查是要走的路:

if (resources) {
    resources.addEventListener("mouseover", function() { ... }, false);
}
于 2013-03-13T09:23:38.570 回答
1

没有与您的数组中的选择器之一匹配的元素。在附加事件之前,做一个简单的检查以确保它不是未定义的。

var object = ["a","input","textarea","select","img","#content",".view"];
for (var i = 0; i < oj.length; i++) {
    var resources = document.querySelector(object[i]);
    if(resources){
    resources.addEventListener('mouseover', function(){alert("test");}, false);
    }
}
于 2013-03-13T09:23:48.100 回答