我正在学习Javascript,我需要一些帮助。我有一份清单。我已经尝试制作一个列表,只需点击一下按钮,就可以从该列表中获取随机歌曲,但它似乎无法正常工作。我的名单在下面,我做错了什么?
<!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>
&#13;
答案 0 :(得分:1)
您的代码几乎是正确的。这是一个合适的版本:
HTML
<div>
<button type="randomSong" onclick="randomSong()">Random Music</button>
<input name="randomSong" id="randomSong">
</div>
修改:
"randomSong"
没有任何属性键)onclick
回调,以便在您点击按钮时发生某些事情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;
}
修改:
onclick
属性引用的函数)答案 1 :(得分:0)
下面的方法显示了如何在javascript中获取随机项:
<div>
<button onclick="findSong();" type="randomSong">Random Music</button>
<input "randomSong" id="randomSong">
</div>
<script>
function findSong() {
var song = ["song1", "song2", "song3", "song4", "song5", "song6"];
var random = Math.floor(Math.random() * (song.length - 1));
document.getElementById("randomSong").setAttribute("value", song[random]);
}
</script>
另见这个小提琴: https://jsfiddle.net/Lt1zgLk9/