简体   繁体   中英

How do I change an image with javascript without an onclick event?

I'm trying to get a dummy username and profile picture to display at random, at a random interval. I also want the usernames to match their respective profile pictures.

I currently I have html that displays the usernames correctly
<p id="usr"></p>
<img id="changeimage" src="" alt="Profile picture">

And javascript like this

var players = ['player1', 'player2', 'player3']
var playerpics = ['player1.jpg', 'player2.jpg', 'player3.jpg'];


var activeuser;
var playerpicker = function (activeuser) {
    usr.innerHTML = players[activeuser];
    changeimage.innerHTML = "<img src='" + playerpics[activeuser] + "' />";

};

setInterval(function () {
    var oneintwelve = Math.floor(Math.random() * 12);

    if (oneintwelve === 3) {
        activeuser = Math.floor(Math.random() * 3);
        playerpicker(activeuser);

    };
}, 1000);

I know I'm doing something wrong with implementing the new IMG tag, forgive me if I'm not doing this the best way, I'm fairly new to this. Thanks for the help.

You're almost there, you can change the src attribute of an image. Also you didn't quite correctly selected the elements.

var playerpicker = function (activeuser) {
    document.getElementById("usr").innerHTML = players[activeuser];
    document.getElementById("changeimage").src= playerpics[activeuser];
};

Check this link, it will help you learn http://www.w3schools.com/jsref/dom_obj_select.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM