简体   繁体   中英

error NULL when get value in array with document.querySelector in javascript?

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);
}

Error TypeError: resources is null , how to fix it ?

I guess the basic check for non-falsy value (element matched the selector) is the way to go:

if (resources) {
    resources.addEventListener("mouseover", function() { ... }, false);
}

There are no elements matching one of the selectors in your array. Do a simple check to make sure its not undefined, before attaching the event.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM