Generating a random link through Javascript/HTML

前端 未结 3 1199
北海茫月
北海茫月 2021-01-07 14:30

I am trying to create a script that allows me to display a hyperlink that redirects the user to a random url selected out of four sites. So far I have created an array for t

相关标签:
3条回答
  • 2021-01-07 15:08

    Here's a simple way to do it.

    <script>
        var sites = [
            'http://www.google.com',
            'http://www.stackoverflow.com',
            'http://www.example.com',
            'http://www.youtube.com'
        ];
    
        function randomSite() {
            var i = parseInt(Math.random() * sites.length);
            location.href = sites[i];
        }
    </script>
    <a href="#" onclick="randomSite();">Random</a>
    
    0 讨论(0)
  • 2021-01-07 15:14
    <a href="javascript:openSite()">Click to go to a random site</a>
    <script>
    var links = [
                  "google.com",
                  "youtube.com",
                  "reddit.com",
                  "apple.com"]
    
               var openSite = function() {
                  // get a random number between 0 and the number of links
                  var randIdx = Math.random() * links.length;
                  // round it, so it can be used as array index
                  randIdx = parseInt(randIdx, 10);
                  // construct the link to be opened
                  var link = 'http://' + links[randIdx];
    
         return link;
        };
    </script>
    
    0 讨论(0)
  • 2021-01-07 15:23

    Here is the code:

    var links = [
              "google.com",
              "youtube.com",
              "reddit.com",
              "apple.com"]
    
    function openSite() {
        // get a random number between 0 and the number of links
        var randIdx = Math.random() * links.length;
        // round it, so it can be used as array index
        randIdx = parseInt(randIdx, 10);
        // construct the link to be opened
        var link = 'http://' + links[randIdx];
            return link;
    };
    
    document.getElementById("link").innerHTML = openSite();
    

    Here is the fiddle: https://jsfiddle.net/gerardofurtado/90vycqyy/1/

    0 讨论(0)
提交回复
热议问题