使用JavaScript指定图像(随机选择)

时间:2015-02-20 17:14:59

标签: javascript html5

Hello guys :)我试图从变量列表中随机生成一个图像,但没有任何工作。我试过这样的事情:

document.querySelector("img").src = variables.img;

它不起作用,因为它改变了我网站上的第一张图片,而不是我希望它改变的图像。我有一个这样的清单:

var songs =
[
    { filename: "http://linktomp3-1.com", title: "title1", album: "---" },
    // Song: title1
    { filename: "http://linktomp3-2.com", title: "title2", album: "---" },
    // Song: title2
    { filename: "http://linktomp3-3.com", title: "title3", album: "---" },
    // Song: title3
    { filename: "http://linktomp3-4.com", title: "title4", album: "---" },
];
    var randomIndex = Math.floor(Math.random() * songs.length);
    var song = songs[randomIndex];
    document.querySelector("source").src = song.filename;
    document.getElementById("songTitle").textContent = song.title;
    document.getElementById("songAlbum").textContent = song.album;

以下是文字前面的表格:

<table width="300">
       <tr>
            <td width="190">
            <b>Made by:</b> <span>Band Title</span><br>
            <b>Title:</b> <span id='songTitle'></span><br><br>
            <b>Album:</b> <span id='songAlbum'></span>
            </td>

            <td width="10">
            </td>
<td width="100">
<img src="http://www.someimg.com/someimg.jpg"></img>
</td>
       </tr>
</table>

<br><br>

<audio class="audio-element" controls="true" preload="none" loop="loop">

<!-- Adding audio sources -->

            <source src="mp3file.mp3" type="audio/mpeg" />
            <br>
            <b>Your outdated browser does not support HTML5. <br>
            Get Mozilla Firefox <a href="https://www.mozilla.org/pl/firefox/new/"> >HERE< </a></b>

</audio>

有没有办法指定我想用Javascript更改的图片?

1 个答案:

答案 0 :(得分:0)

提供您想要更改ID的图像,以便您可以像对待跨度一样专门定位它。

<td width="100">
    <img id="bandImg" src="http://www.someimg.com/someimg.jpg"></img>
</td>

http://jsfiddle.net/1b1nt95c/11/

相关问题