如何使用本地文件在香草JavaScript中添加图片?

时间:2018-11-14 05:14:44

标签: javascript html

我对编码非常陌生,我们刚刚开始使用javascript(vanilla)。目前,我们正在开发猜词游戏,我正在尝试以图像为线索。这些图像将附加到单词及其在索引上的位置。我已经研究过网络,但对执行此操作的各种不同方式感到困惑。我尝试了几次,但似乎无法将图像链接到该图像所在的资产文件夹。

alert("Guess the video game!")
var totalGuesses = 9; //total number of guesses
var words = ["SuperMario64", "GoldenEye", "Contra", "StreetFighter", 
"MarioKart", "MortalKombat", "StarFox"];
console.log(words);
var userGuess = [] //keystrokes guessed
var guessesLeft = 0; //amount of guesses left
var wordsGuessed = [] //word being guessed
var computerChoices;
var wins = 0;
var losses = 0;
var mario = document.createElement("img");
mario.setAttribute("src" , "assets/images/Mario.jpg");



userGuess = [];
wordsGuessed = [];

document.onkeyup = function (event) {
alert("Press any key to start")
wordsGuess = String.fromCharCode(event.keyCode);
userGuess = event.key;
//generate random choice of words

Computerchoice = words[0] //Math.(Math.random() * (words.length));

if (computerChoices == words[0]) {
    var mario = document.createElement("img");
    mario.setAttribute(src='assets/images/Mario.jpg');
    document.getElementById("clue").append(mario);

}

}

2 个答案:

答案 0 :(得分:0)

唯一的问题是第二次设置src元素的img属性:

mario.setAttribute(src='assets/images/Mario.jpg');

这是无效的JavaScript。将其更改为此(已在您的代码中-持续使用技术)可解决您的问题:

mario.setAttribute("src", "assets/images/Mario.jpg");

答案 1 :(得分:0)

您可以这样简单地设置:

_userManager.GetUserId(User)