简体   繁体   English

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

[英]How to append an image in vanilla javascript using a local file?

I'm very new to coding and we have just started javascript(vanilla). 我对编码非常陌生,我们刚刚开始使用javascript(vanilla)。 Currently we are working on a word guessing game and I'm trying to have images as clues. 目前,我们正在开发猜词游戏,我正在尝试以图像为线索。 These images would be attached to the word and its location on the index. 这些图像将附加到单词及其在索引上的位置。 I've researched the web but I'm confused by the various different ways to do this. 我已经研究过网络,但对执行此操作的各种不同方式感到困惑。 I've tried a few but I can't seem to get the image to link to my assets folder where the image is located. 我已经尝试了几次,但似乎无法将图像链接到该图像所在的资产文件夹。

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);

}

}

The only problem is the second time you are setting the src attribute of the img element: 唯一的问题是第二次设置img元素的src属性:

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

This is invalid JavaScript. 这是无效的JavaScript。 Changing it to this (which is already in your code - keep using techniques consistently) fixes your problem: 将其更改为此(已在您的代码中-持续使用技术)可解决您的问题:

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

You can simply set like this: 您可以这样简单地设置:

var mario = document.createElement("img");
mario.src = "assets/images/Mario.jpg";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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