gpt4 book ai didi

javascript - 如何将函数中的变量作为参数传递给匿名函数以充当变量

转载 作者:行者123 更新时间:2023-12-03 12:16:42 25 4
gpt4 key购买 nike

我试图调用一个函数,但然后给它一些需要从另一个函数使用的变量,而不会污染全局命名空间。

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

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

关于javascript - 如何将函数中的变量作为参数传递给匿名函数以充当变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24657120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com