简体   繁体   中英

Javascript function works but returns undefined

I'm trying to build a function that looks for all elements with the 'filter' rel in my page, and then adds them to a js object.

The function itself seems to work fine when I use console.log within the function, however, when I attempt to call the function anywhere it returns undefined. I realize that this is a common issue with asynchronous calls, but I didn't think that was the case here:

function getFilters() {
jQuery(document).ready(function($) {
    var filters = new Array();
    $("[rel=filter]").each(function(i,e){
        var type = $(e).attr('type');
        if(type == 'checkbox') { if($(e).is(':checked')) var val = $(e).prop('checked'); }
        else if(type == 'radio') { if($(e).is(':checked')) var val = $(e).val(); }
        else var val = $(e).val();
        if(val) filters.push({name : $(e).attr('name'), value : val});
    });
    return filters;
});
}

Again, when I run console.log(filters); in place of return filters; my data pulls up just fine. When I attempt to return it though, it just results in undefined. Any help is much appreciated.

If you're expecting getFilters() to return a value, that's your problem. All getFilters() does is register an event handler (it doesn't return anything).

You probably want something like this:

function getFilters() {
    var filters = new Array();
    $("[rel=filter]").each(function(i,e){
        var type = $(e).attr('type');
        if(type == 'checkbox') { if($(e).is(':checked')) var val = $(e).prop('checked'); }
        else if(type == 'radio') { if($(e).is(':checked')) var val = $(e).val(); }
        else var val = $(e).val();
        if(val) filters.push({name : $(e).attr('name'), value : val});
    });
    return filters;
}


$(document).ready(function() {
    var filters = getFilters();
    // do something with filters
});

The problem is that the function getFilters actually returns nothing, because it just invokes jQuery(document).ready(...);, just binding a function to run later. The anonymous function that returns filters is actually invoked after page is ready, but caller of getFilters does not take the return value.

You need to define filters var one level up or make it global. Now it's local in the function defined by jQuery, so it's not visible in getFilters.

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