显示图像阵列onclick按钮

时间:2016-12-11 15:25:39

标签: javascript arrays onclick

HTML:我设置了按钮onclick" myFunction"现在我希望图像显示在

<body>



<p>Click the button to see some images</p>


<button onclick="myFunction()">See the Images!!!</button>



<script src="js2/images.js">





</script>

</body>

JS:需要显示图像onclick ...不确定我是否在正确的轨道,因为我是JS的初学者...我似乎无法显示图像,只有图像的src名称。 ...

function myFunction() {

pge = new Array ()

 pge[4] = "../images/sky3.jpg"


 pge[3] = "../images/sky8.jpg"

 pge[2] = "../images/sky7.jpg"

 pge[5] = "../images/sky6.jpg"

 pge[0] = "../images/sky5.jpg"

 pge[1]= "../images/sky4.jpg"

 pge[6] = "../images/sky1.jpg"  

 pge[7] = "../images/sky2.jpg"




 for (i=0;i<=pge.length-1;i++) {


var img = document.createElement("img");

????????

}


}

3 个答案:

答案 0 :(得分:0)

添加行

img.setAttribute("src", pge[i]);

在你的??????部分

答案 1 :(得分:0)

这样的事情应该可以解决问题。 (部分基于How to display image with javascript?

<!DOCTYPE html>
<html>
<head>
	<title>Test</title>
</head>
<body>	
	<p>Click the button to see some images</p>

	<button onclick="myFunction()">See the Images!!!</button>

	<script>
		function show_image(src, width, height, alt) {
			var img = document.createElement("img");
			img.src = src;
			img.width = width;
			img.height = height;
			img.alt = alt;

			// This next line will just add it to the <body> tag
			document.body.appendChild(img);
		}
	  
		function myFunction() {
			var pge = ["http://www.w3schools.com/graphics/pic_the_scream.jpg", "http://www.w3schools.com/images/colorpicker.gif"];

			for(var i = 0; i < pge.length; i++){
				show_image(pge[i], 100, 200, i)
			}
		}          
	</script>
</body>
</html

答案 2 :(得分:0)

单击按钮时,HTML需要一个显示图像的位置。您可以使用CSS来设置div的样式。

<body>
        <p>Click the button to see some images</p>

        <button onclick="myFunction()">See the Images!!!</button>

        <div id="showImg"></div>        

        <script src="js2/images.js"></script>    
</body>

您不必使用Array构造函数。将图像存储在数组中,如下所示,使用for循环遍历数组,然后使用innerHTML属性创建img标记,定位图像并显示它们。您可以使用CSS来设置图像样式。

    var pge = ["sky3.jpg", "sky8.jpg", "sky7.jpg", "sky6.jpg", "sky5.jpg", "sky4.jpg", "sky1.jpg", "sky2.jpg"];
var showImg = document.getElementById("showImg");

var myFunction = function(){
    for(var i = 0; i < pge.length; i++)
    {
        showImg.innerHTML = "<img src='images/" + pge[0] + "'/> <img src='images/" + pge[1] + "'/> <img src='images/" + pge[2] + "'/> <img src='images/" + pge[3] + "'/> <img src='images/" + pge[4] + "'/> <img src='images/" + pge[5] + "'/> <img src='images/" + pge[6] + "'/> <img src='images/" + pge[7] + "'/>";
    }
}