简体   繁体   English

使用javascript中的document.querySelector在数组中获取值时错误NULL?

[英]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 ? 错误TypeError: resources is null ,如何解决?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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