繁体   English   中英

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

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

我正在尝试调用一个函数,但是然后给它提供一些需要从另一个函数使用的变量,而不会污染全局名称空间。

这有效,但将这些变量声明为我不想要的全局变量。

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

我想要这样的东西,我只是不知道语法。

要调用的功能

$.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);
    });
}

函数调用上面的函数。

$(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);
});

谢谢。

您需要在feed_g函数中声明参数。 否则,该函数将不知道如何引用其收到的参数。

$.feed_g = function(post_source, postid){

这些参数名称不必与传递给函数的名称相同。 例如,考虑这个简化的例子

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