简体   繁体   中英

TypeError: undefined is not a function jQuery

I'm new to jQuery and I can get it to sometimes work, however, for some reason, when I try to call a function, it gives me the title error, but if I do it in developer tools, it works fine.

http://jsfiddle.net/otanan/pmzzLo3e/#&togetherjs=AezijhfBrj

It seems to work fine when retrieving the classes from the DOM, but not when I call a function such as

.click(function() {});

Here's the code:

var downloads = $(".info"),
    className = "info_clicked";

for(var i in downloads)
{
    downloads[i].click(function()
    {
        if(!this.hasClass(className))
            this.addClass(className);
        else
            this.removeClass(className);
    });
}

When you access a jQuery collection as an array, it returns the DOM elements, not jQuery objects. You should use .each() rather than for (i in downloads) :

downloads.each(function() {
    $(this).click(function() {
        if (!$(this).hasClass(className)) {
            $(this).addClass(className);
        } else {
            $(this).removeClass(className);
        }
    });
});

You could also simplify the whole thing to:

downloads.click(function() {
    $(this).toggleClass(className);
});

Most jQuery methods automatically iterate over all the elements in a collection if it makes sense to do so (the notable exceptions are methods that return information from the element, like .text() or .val() -- they just use the first element). So you generally only have to iterate explicitly if you need to do different things for each element. This is one of the great conveniences of using jQuery rather than plain JS: you rarely have to write explicit iterations.

I think the issue is that you're attempting to call a jQuery function on an object that is no longer a jQuery object.

For example you're saying $(".info") . Which retrieves a single jQuery object. As soon as you index that object downloads[i] it is no longer a jQuery object, it is a plain HTML element and does not have a click function available.

What you really need to do is get the jQuery object for the indexed item:

var downloads = $(".info"),
className = "info_clicked";

for(var i = 0; i < downloads.length; i++)
{
    $(downloads[i]).click(function()
    {
        if(!this.hasClass(className))
            this.addClass(className);
        else
            this.removeClass(className);
    });
 }

试试吧:

$(downloads[i]).click(function(){ //...

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