简体   繁体   中英

Uncaught Type Error in javascript: object has no method

Uncaught TypeError: Object 0 has no method 'addEventListener' 

var A={};
A.addEventsToClassName=function(event,className,func)
{
    var a=document.getElementsByClassName(className);
    for(var b in a)
        {
            b.addEventListener(event,func,false);
        }
};

Object b is meant to be an element object once the function is called later in the code. How can I prevent this error?

A for (var b in a) will give the property names within a , not the actual values; so you need to dererefence a when you want to use them.

a[b].addEventListener(event, func, false);

Also, it's an Array like data structure, so you should iterate it as such:

for (var i = 0; i < a.length; ++i) {
    a[i].addEventListener(event, func, false);
}

b is not an object nor an element, it is a string ( "0" ). for...in gives you the keys not the value.


Don't use for(var b in a) to loop through a NodeList (it will loop through not only the properties of itself but also the properties inherited from its parent), do this instead:

for(var i = 0; i < a.length; a++){
    a[i].addEventListener...
}

If you ask why, then take this for example,

for(var a in document.querySelectorAll("body")){
    console.log(a);
}

>"0"
>"length"
>"item"

You can see that for...in does not work in this case since length and item are not actually in the list but still properties inherited.

The b is probably a index not your object . Perhaps you want write like this:

a[b].addEventListener(event,func,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