如何在javascript中从html调用img?

时间:2017-06-02 22:04:24

标签: javascript html

可以在js数组中放置多个图像,当调用该功能时,其中一个图像(随机)将弹出到屏幕上?

如果没有,我如何使用.innerHTML将图片网址放到<img src="">

3 个答案:

答案 0 :(得分:0)

自动随机图片:

var images = ["https://www.w3schools.com/images/compatible_chrome.gif",
"https://www.w3schools.com/images/compatible_edge.gif", 
"https://www.w3schools.com/images/compatible_firefox.gif", 
"https://www.w3schools.com/images/compatible_safari.gif", 
"https://www.w3schools.com/images/compatible_opera.gif"]

function getImage() {
    var x = Math.floor((Math.random() * images.length));
    document.getElementById("demo").innerHTML = "<img src=" + images[x] + ">";
}

getImage();
<div id="demo"></div>

答案 1 :(得分:-1)

不确定

&#13;
&#13;
// Store the image sources in an array:
var imgs = ["http://logok.org/wp-content/uploads/2014/03/abc-gold-logo.png",
            "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/NBC_logo.svg/779px-NBC_logo.svg.png",
            "https://s-media-cache-ak0.pinimg.com/originals/96/e6/d9/96e6d9e141ac42bf9aad1aaae0a15c61.jpg", 
            "http://fontmeme.com/images/CNN-Logo.jpg",
            "http://logok.org/wp-content/uploads/2014/12/TBS-logo-blue.png",
            "http://www.doddlenews.com/wp-content/uploads/2012/05/fox-tv-logo.jpg"];

// Get reference to the img element
var img = document.getElementById("myImage");

function getRandomImage(){
  // Get random number between 0 and 3 (the length of the array)
  var rnd = Math.floor(Math.random() * imgs.length);

  // Set the src and the alt to a random image from the array
  img.src = imgs[rnd];
  img.alt = imgs[rnd];
}

// Get reference to the button
var btn = document.getElementById("getImage");

// When button is clicked, run function
btn.addEventListener("click", getRandomImage);
&#13;
img { width:75px; }
&#13;
<button id="getImage">Click to get random image</button>
<br>
<img src="https://pisces.bbystatic.com/BestBuy_US/en_US/images/abn/2014/tvv/cat/tv/tv_size4a.jpg;maxHeight=333;maxWidth=333" id="myImage">
&#13;
&#13;
&#13;

另外,仅供参考,.innerHTML仅适用于具有&#34;内容&#34;的元素。 img元素没有结束标记,因此,它不能包含&#34;它的开始和结束标签之间的任何东西。

答案 2 :(得分:-1)

你不需要为此使用innerHTML。而是使用.setAttribute()

示例:

 <img id="image1" src="" />

 document.getElementById('image1').setAttribute("href", "xyz.html");

变为:

 <img id="image1" src="xyz.html" />