简体   繁体   中英

How to pass a variable from a function as an argument to an anonymous function to work as a variable

I'm trying to call a function, but then give it some variables it needs to use from another function without polluting the global namespace.

This works but declares these variables as global which i don't want.

$(document).on('click', '.News_Header_Holder', function () {
    postid = $(this).attr('data-postid');
    post_source = $(this).attr('data-source');
    $.feed_g();
});

I want something like this, i just don't know the syntax.

Function to be called

$.feed_g = function () {
    $('.Loader_G').fadeIn(500);
    var data = {
        source: post_source,
        pid: postid,
    }
    $.ajax({
        type: "POST",
        complete: function () {
            $('.Loader_G').fadeOut(500);
        },
        data: data,
        url: "php/feed.php",
    }).done(function (f) {
        $('#Feed_G').html(f);
    });
}

Function to call the above function.

$(document).on('click', '.News_Header_Holder', function () {
    var postid = $(this).attr('data-postid');
    var post_source = $(this).attr('data-source');
    $.feed_g(post_source, postid);
});

Thanks.

You need to declare the parameters in the feed_g function. Otherwise the function won't know how to refer to the parameters it received.

$.feed_g = function(post_source, postid){

These parameter names do not need to be the same names as what you pass to the function. For example, consider this simplified example

function frob(x, y){ console.log("Hello", x, y) }

frob("a", "b");

var q = 1;
var w = 2;
frob(q, w);

var x = 10;
var y = 20;
for(y, x);

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