我如何显示随机数组没有点击按钮

How do I display randomly an array without click on the button?

本文关键字:数组 按钮 随机 何显示 显示      更新时间:2023-09-26

我想有一个按钮的页面,当我点击按钮的文本应该显示。使用Javascript从不同的数组中随机抽取文本。在我的项目中,除了一件事,一切都很顺利:在第一次加载页面时,我看到没有文本,只有按钮。如何使其中一个数组随机选择并显示在第一个页面加载(不单击按钮)

<!DOCTYPE html>
<html>
<head>
    <script>
        function myFunction() {
            var quotes = [{
                text: " <br>    1   <br><br>    2   <br><br>    3   ",
            }, {
                text: " <br>    4   <br><br>    5   <br><br>    6   ",
            }, {
                text: " <br>    7   <br><br>    8   <br><br>    9   ",
            }, ];
            var quote1 = quotes[Math.floor(Math.random() * quotes.length)];
            document.getElementById("quote1").innerHTML =
                '<p><font size="7">' + quote1.text + '</font></p>';
        }
    </script>
</head>
<body>
    <center>
        <div id="quote1"></div>
        <br>
        <br>
        <br>
        <br>
        <br>
        <center>
            <a href="#" onclick="myFunction()">Next</a>
        </center>
    </center>
</body>
</html>

谢谢!

在页面加载时调用

window.onload = function(){
   myFunction();
}

加载页面后调用该函数

<body onload="myFunction()">

将所有内容放到文档末尾的函数中:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<center>
<div id="quote1"></div>
<br>
<br>
<br>
<br>
<br>
<center>
<a href="#" onclick="randomQuote()">Next</a>
</center>
</center>
</body>
<script>
var randomQuote = function() {
    var quotes = [
       {text:" <br>    1   <br><br>    2   <br><br>    3   ",},
       {text:" <br>    4   <br><br>    5   <br><br>    6   ",},
       {text:" <br>    7   <br><br>    8   <br><br>    9   ",},
     ];
     var quote1 = quotes[Math.floor(Math.random() * quotes.length)];
     document.getElementById("quote1").innerHTML=
          '<p><font size="7">' + quote1.text + '</font></p>';
 };
 randomQuote();
</script>
</html>

最后一行将立即执行函数