简体   繁体   中英

Accessing variables from one function to another in JavaScript

To start, here's a small project I made that throws a new fact every time the user presses the New Fact button. Source code available here . Then I made a Twitter button to tweet that quote.

As you can see in main.js file, there's a variable called quotes which is an array of 40 quotes (snipped in the code below).

// 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");
        });
    });

Whenever the user clicks the Tweet button, it opens up multiple twitter tabs for each i . I want the tab to be opened for the current quote only. I tried keeping the two functions separate, and not nested but then quotes[i] becomes inaccessible resulting in undefined .

Since you're storing the text that you're URI-encoding in the .lead element, here's one way you can separate the functions:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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