Javascript / HTML-如何从数组中随机选择并显示它

时间:2018-11-27 04:02:15

标签: javascript html

我已经开始练习html / javascript了,因为自从我学习了基础知识以来已经很长时间了,我想对此做得更好。无论如何,我一直在一个简单的html页面上工作,其中有一个包含100个电影名称的数组,并且每次加载该页面时,我都希望javascript从我创建并显示的数组中选择随机电影,但是无论如何我做到了,我无法显示它。请帮我解决我犯错的地方。这是我到目前为止的内容:

<!DOCTYPE html>
    <html>
        <head>
            <title>Movie Roulette</title>
        </head>

        <body>

            <h2 style="text-align:center">
                Your Movie for Tonight is: 
            </h2>

            <script>
                var theList = ["The Godfather (1972)", "The Shawshank Redemption (1994)", ... + 98 other movie names];
                var randomPick = theList[Math.floor(Math.random()*theList.length)];
                  document.body.innerHTML = randomPick;

            </script>

        </body>   
    </html> 

2 个答案:

答案 0 :(得分:1)

menu bar在这种情况下不正确。相反,请在document.body.innerHTML = randomPick;内创建一个跨度并为其添加一个ID。然后在跨度内添加电影名称

h2
var theList = ["The Godfather (1972)", "The Shawshank Redemption (1994)", 'someNameA', 'someNameB', 'someNameC', 'someNameD', 'someNameE'];
var randomPick = theList[Math.floor(Math.random() * theList.length)];
document.getElementById('movieName').innerHTML = randomPick;

使用<h2 style="text-align:center"> Your Movie for Tonight is:<span id='movieName'></span> </h2>将从体内删除其他dom元素

document.body.innerHTML
var theList = ["The Godfather (1972)", "The Shawshank Redemption (1994)", 'someMovA', 'someMovB', 'someMovJ', 'someMovR', 'someMovF'];
var randomPick = theList[Math.floor(Math.random() * theList.length)];
document.body.innerHTML = randomPick;

答案 1 :(得分:0)

您的代码似乎可以正常工作@taho。您声明并定义了theList部分的数组script并不是真正的字符串数组。只需将它的, and 98 other movies的最后一部分删除即可,并替换为其他字符串,例如前两部电影。

还有一个建议的改进:不用用电影名称替换整个body,而是在div中创建ID为spanbody并插入那里的电影名称。

<!DOCTYPE html>
<html>

<head>
  <title>Movie Roulette</title>
</head>

<body>

  <h2 style="text-align:center">
    Your Movie for Tonight is:
  </h2>
  
  <span id = "movie_tonight">
  </span>
  
  <script>
    var theList = ["The Godfather (1972)", "The Shawshank Redemption (1994)", "Jaws", "Kung-Fu Panda", "The Revenant", "Get Out"];
    var randomPick = theList[Math.floor(Math.random() * theList.length)];
    document.getElementById("movie_tonight").innerHTML = randomPick;
  </script>

</body>

</html>