문제

I am a newbie and I am trying to create an HTML page with buttons that have random background colors based on colors in an array. This is what I have right now (although it doesn't work). I am hoping someone can give me advice on how to fix this so that it does what I want.

    #button {
            width: 100px;
            height: 100px;
        }

    </style>
</head>

<body>
    <div id="testForm">
        <button id="button">
            Testing
        </button>
    </div>


    <script type="text/javascript">

        $(document).ready(function()
        {
            var myColors = new Array();
            myColors[0] = "#2672EC";
            myColors[1] = "#97009F";
            myColors[2] = "#094DB5";
            myColors[3] = "#00A300";
            myColors[4] = "#DA532C";
            myColors[5] = "#AF1A3F";
            myColors[6] = "#613CBC";
            myColors[7] = "#008AD2";

            var rand = Math.floor(Math.random()*myColors.length); 
            $('#button').css("background-color", myColors[rand]); 
        }


    </script>
도움이 되었습니까?

해결책 2

Close the ready function

DEMO

 $(document).ready(function()
            {
                var myColors = new Array();
                myColors[0] = "#2672EC";
                myColors[1] = "#97009F";
                myColors[2] = "#094DB5";
                myColors[3] = "#00A300";
                myColors[4] = "#DA532C";
                myColors[5] = "#AF1A3F";
                myColors[6] = "#613CBC";
                myColors[7] = "#008AD2";

                var rand = Math.floor(Math.random()*myColors.length); 
                $('#button').css("background-color", myColors[rand]); 
            });  //missed to close

다른 팁

var myArray = [ "#97009F","#094DB5","#00A300","#DA532C","#AF1A3F","#613CBC","#008AD2"];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top