在JavaScript中从一个函数访问变量到另一个函数

时间:2016-12-28 23:14:12

标签: javascript jquery twitter

首先,我做了small project每次用户按下New Fact按钮时都会抛出一个新事实。可用的源代码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");
        });
    });

每当用户点击推文按钮时,它会为每个i打开多个推文选项卡。我希望仅为当前报价打开选项卡。我尝试将两个函数分开,而不是嵌套,但后来quotes[i]无法访问,导致undefined

1 个答案:

答案 0 :(得分:1)

由于您在.lead元素中存储了您进行URI编码的文字,因此您可以通过以下方式分离这些功能:

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