Random slogan generator with using javascript's switch

前端 未结 3 1948
一生所求
一生所求 2021-01-07 14:46

I have got little problem. I\'m learning javascript and I wanted to create random slogan generator for my site with using switch.

So I created this html

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

    You left part of the code outside the rndqu() function. I forked and corrected your fiddle here: http://jsfiddle.net/BwJ7s/

    Here's the corrected JS code:

    var qu;
    var slogan;
    function rndqu(n)
    {
        var random = function(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
        };  
        qu = random(1, 3);
    
        switch(qu){
            case 1:
                slogan = "Here is the 1";
                break;
            case 2:
                slogan = "Here is the 2";
                break;
            case 3:
                slogan = "Woah";
                break;
            default:
                slogan = "Really?";
        }
        document.getElementById("quote").innerHTML = slogan;
    }
    
    0 讨论(0)
  • 2021-01-07 15:27

    I would use an array instead of a switch statement for this, to make it more flexible. For example:

    var quotesList = ["I'm a great guy!", "Not even kidding.", "Just incredible."];
    
    var randQuote = function(quotes) {
        var choice = Math.floor(Math.random() * quotes.length);
        return quotes[choice];
    }
    
    document.getElementById("quote").innerHTML = randQuote(quotesList);
    

    This way, the size of the quote array can be changed freely without having to change any of the code.

    Demo: jsfiddle

    0 讨论(0)
  • 2021-01-07 15:34

    Fixed here http://jsfiddle.net/NX3cz/13/

    var qu;
    var slogan;
    function rndqu(min, max){
    
        qu =  Math.floor(Math.random() * (max - min + 1)) + min;
    
        switch(qu){
            case 1:
                slogan = "Here is the 1";
                break;
            case 2:
                slogan = "Here is the 2";
                break;
            case 3:
                slogan = "Woah";
                break;
            default:
                slogan = "Really?";
        }
        document.getElementById("quote").innerHTML = slogan;
    }
    
    rndqu(1, 3);
    

    Your code was overly complicated also notice, in jsfiddle don't add a body onload="()" function. Jsfiddle does that for you.

    If you want to do it onbodyload on a real webpage wrap your code in this:

    window.onload = (function(){
        //your code goes here
    })
    

    or include your script at the bottom of the html file.

    Whenever possible best practice is to avoid inline javascript in your html.

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