简体   繁体   English

用javascript加载图像。 我的语法哪里有错?

[英]Loading and image with javascript. Where is my syntax wrong?

I am learning MVC using vanilla Javascript. 我正在使用香草Javascript学习MVC。 I am trying to load an image when a button is pressed, but I believe my syntax is off. 我试图在按下按钮时加载图像,但是我相信我的语法已关闭。 Any ideas? 有任何想法吗?

here are my scripts. 这是我的脚本。 I think the problem is in the View script, at the document.getElementById line. 我认为问题出在View脚本的document.getElementById行上。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <script src="Controller.js"></script>
    <script src="View.js"></script>
    <script src="Model.js"></script>
    <title></title>
</head>

<body onload="buildImgArr()">

<div align="center">
<img id="imageFrame" >
</div>

<div  align="center">
<button id="loadImage" type="button" onclick="controlIMG()" >Click to load image</button>
</div>

</body>

</html>

control script 控制脚本

function controlIMG(){

var randImg = randomImg();

loadIMG(randImg);
}

Model script 模型脚本

var myImages = new Array(2);

function buildImgArr(){
    //alert("In Array");
    myImages[1] = "hiragana/A.PNG";
    myImages[2] = "hiragana/CHI.PNG";
}

function randomImg(){
    //alert("in model");
    var rand = myImages[Math.floor(Math.random() * myImages.length)];
    return rand;
}

View script 查看脚本

function loadIMG(imgsrc){
    alert("In view " + imgsrc);
    //text-align:center; margin: 0px auto; display:block
    document.getElementById("imageFrame").innerHTML = '<img src="imgsrc">';

}

You will need to set the attribute of image using setAttribute . 您将需要使用setAttribute设置图像的属性。 Here the use of innerHTML is wrong as it will try to add a html , but you just need to set the src of the img 在这里,使用innerHTML是错误的,因为它将尝试添加html,但是您只需要设置imgsrc

 function controlIMG() { var randImg = randomImg(); loadIMG(randImg); } var myImages = new Array(2); function buildImgArr() { myImages[1] = "https://media.istockphoto.com/photos/evening-in-the-forest-picture-id494297755?k=6&m=494297755&s=612x612&w=0&h=qn663JrZYf2hpu7SZc-SlrwrR5HjNr3yVcfyDqKHQmg="; myImages[2] = "https://d1ljaggyrdca1l.cloudfront.net/wp-content/uploads/2017/02/Header-luxury-glass-suite-at-andbeyond-phinda-forest-lodge-on-a-luxury-safari-in-south-africa-1600x900.jpg"; } function randomImg() { var rand = myImages[Math.floor(Math.random() * myImages.length)]; return rand; } function loadIMG(imgsrc) { // using setAttribute method to dynamically set the src document.getElementById("imageFrame").setAttribute('src', imgsrc); } 
 .imageHolder { width: 100px; height: 100px; } img { width: 100%; height: 100%; } 
 <body onload="buildImgArr()"> <div align="center" class="imageHolder"> <img id="imageFrame"> </div> <div align="center"> <button id="loadImage" type="button" onclick="controlIMG()">Click to load image</button> </div> </body> 

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

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