开发者

De-Anonymizing an Anonymous Function in jQuery

This is probably quite a simple problem, but it's causing me to scratch my head, so I'm posting it here.

I have some jQuery in the following form:

if (jQuery('.SearchRegions:checked').length == 0) { 

jQuery('.SearchRegions').each(function(){

        //code

    });

} else {

jQuery('.SearchRegions:checked').each(function(){

        //the same code     

    });

}

Obviously it seems ridiculous to repeat a big block of code inside each of these functions. But when I tried to name and move the function, it all seemed to break down - perhaps because of issues with scope and/or开发者_JS百科 jQuery(this) inside the function no longer referring to the same object?

Can anyone help me by posting a general idea of what my code should look like? (Or any other optimisings or recastings to make it work would be much appreciated!)


You can definitely just define a function and use it by name:

function someHandler(event) {
  // code code code
}

jQuery('.SearchRegions').each(someHandler);

Note that when you refer to the function by name, you don't include "()".


Assuming that closures are indeed the problem, you can parameterize your "anonymous" function to pass those values in to it. For example:

function eachRegion(values, $container, foo) {
    // common code which uses scope variables `values`, `$container`, and `foo`
}

// elsewhere, in code defining `values`, `$container`, and `foo`...

if (jQuery('.SearchRegions:checked').length == 0) { 
    jQuery('.SearchRegions').each(function(){
        eachRegion(values, $container, foo);
    });
} else {
    jQuery('.SearchRegions:checked').each(function(){
        eachRegion(values, $container, foo);
    });
}


You could define your function as a variable and use that in your each method call.

var yourEachFunction = function(){$("ul").append("<li>" + $(this).val() + "</li>");}

if (jQuery('.SearchRegions:checked').length == 0) {
    jQuery('.SearchRegions').each(yourEachFunction );
} else {
    jQuery('.SearchRegions:checked').each(yourEachFunction );
}

Example of this working on jsfiddle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜