简体   繁体   English

如何将变量从函数作为参数传递给匿名函数以充当变量

[英]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. 您需要在feed_g函数中声明参数。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM