gpt4 book ai didi

javascript - 在 JavaScript 中从一个函数访问另一个函数的变量

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

首先,这里有一个 small project我让每次用户按下“新事实”按钮时都会抛出一个新事实。可用源代码 here 。然后我创建了一个 Twitter 按钮来发布那段引用。

正如您在 main.js 文件中看到的,有一个名为quotes 的变量,它是一个包含 40 个引号的数组(在下面的代码中进行了剪裁)。

// var quotes defined above, an array of 40 quotes

$(".quoter").click(function() {

// To generate a random number
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1) + myMin);
}

i = randomRange(0, 40);
//Using the random number generated above to fetch a quote
$(".lead").text(quotes[i]);

var uriLink = encodeURIComponent(quotes[i]);

$(".tweeter").click(function(){
window.open("https://twitter.com/intent/tweet?text="+uriLink+, "_blank");
});
});

每当用户单击 Tweet 按钮时,它都会为每个 i 打开多个 Twitter 选项卡。我希望仅针对当前报价打开该选项卡。我尝试将两个函数分开,而不是嵌套,但随后 quotes[i] 变得无法访问,导致 undefined

最佳答案

由于您将 URI 编码的文本存储在 .lead 元素中,因此可以采用以下一种方法来分隔函数:

$(".quoter").click(function() {
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1) + myMin);
}

i = randomRange(0, 40);

$(".lead").text(quotes[i]);
});

$(".tweeter").click(function() {
var uriLink = encodeURIComponent($(".lead").text());
window.open("https://twitter.com/intent/tweet?text=" + uriLink + , "_blank");
});

关于javascript - 在 JavaScript 中从一个函数访问另一个函数的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41371016/

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