admin管理员组

文章数量:1277896

I'm learning Javascript and i need some help. I have a list. I've tried to make a list, where you can, by the click of a button, get a random song from that list, but it doesn't seem to work. My list is down below, what am i doing wrong?

<!DOCKTYPE html>
<html>
<head>
</head>
<body>

<div>
  <button type="randomSong">Random Music</button>
  <input "randomSong" id="randomSong">
</div>

<script>

var song = Array("song1", "song2", "song3", "song4", "song5", "song6");

var randomSong = song[Math.floor(Math.random()*song.length)];

</script>

</body>
</html>

I'm learning Javascript and i need some help. I have a list. I've tried to make a list, where you can, by the click of a button, get a random song from that list, but it doesn't seem to work. My list is down below, what am i doing wrong?

<!DOCKTYPE html>
<html>
<head>
</head>
<body>

<div>
  <button type="randomSong">Random Music</button>
  <input "randomSong" id="randomSong">
</div>

<script>

var song = Array("song1", "song2", "song3", "song4", "song5", "song6");

var randomSong = song[Math.floor(Math.random()*song.length)];

</script>

</body>
</html>

Share Improve this question edited Feb 1, 2016 at 8:20 Martin Grønne asked Feb 1, 2016 at 8:15 Martin GrønneMartin Grønne 411 gold badge1 silver badge3 bronze badges 2
  • 1 Well for one there's no sange variable. The other problem is that you're not doing anything with the selected song, the button, or the input (which has malformed HTML btw). – user1726343 Commented Feb 1, 2016 at 8:20
  • Your JS code works, you just need to put it back into the HTML and then you're done. – Henrik Andersson Commented Feb 1, 2016 at 8:20
Add a ment  | 

2 Answers 2

Reset to default 10

Your code is almost correct. Here is a proper version:

HTML

<div>
  <button type="randomSong" onclick="randomSong()">Random Music</button>
  <input name="randomSong" id="randomSong">
</div>

Modifications:

  • add an attribute name to the input (you had "randomSong" without any attribute key)
  • use an onclick callback, so that something happens when you click your button

JS

var song = Array("song1", "song2", "song3", "song4", "song5", "song6");

function randomSong() {
  var randomSong = song[Math.floor(Math.random() * song.length)];
  document.getElementById('randomSong').value = randomSong;
}

Modifications:

  • wrap your random code into a function (the one referenced by the onclick attribute of your button)
  • assign the result to the input

The method below shows how to get a random item in javascript:

const songs = ["song1", "song2", "song3", "song4", "song5", "song6"];

function findSong() {
  let randomIndex = Math.floor(Math.random() * songs.length);
  document.getElementById("randomSong").setAttribute("value", songs[randomIndex]);
}
<div>
  <button onclick="findSong();" type="randomSong">Random Music</button>
  <input "randomSong" id="randomSong">
</div>

本文标签: javascriptPick a random item from a listStack Overflow