Reputation: 21
I apologize in advance for the childish question, but I'm a novice in javascript.
The simple code below is expected to change an image in a web page. Indeed, a click on one of the links A1 and A2 does the job; on the contrary, on B1 and B2 doesn't.
May be its because a function can't take an array's element in itself as an argument and requires some sort of reference to its content ?
I have seen this question How to pass an array as argument to a function in javascript?, but, if I understood rightly, it is about passing an array as a whole: "Passing arrays to functions is no different from passing any other type ...".
Thanks for your attention !
<HTML>
<HEAD>
<TITLE></TITLE>
<script type="text/javascript">
var images = new Array["1.bmp","2.bmp"];
function changeImage(a) {
document.getElementById("image").src=a;
}
</script>
</HEAD>
<BODY>
<P onclick="changeImage('1.bmp');">A1</P>
<P onclick="changeImage('2.bmp');">A2</P>
<P onclick="changeImage(images[0]);">B1</P>
<P onclick="changeImage(images[1]);">B2</P>
<P onclick="changeImage(images[0]);window.alert(images[0]);">C1</P>
<P onclick="changeImage(images[1]);window.alert(images[1]);">C2</P>
<P><img id="image" src="3.bmp"></P>
</BODY>
</HTML>
Upvotes: 0
Views: 142
Reputation: 5233
The problem arising with your code is that images[] is a Javascript reserved value. This is referencing the images in the DOM of your document.
If you inspect your image by right clicking it and clicking "Inspect Element" you will find that it is injecting an object into the src of your <img>
element. This object is the image element itself.
Simply changing your array to look like this will work:
var imgs = ["1.bmp","2.bmp"];
Upvotes: 0
Reputation: 1571
Your images
array is never properly defined.
If defining an array using new Array
you have to call it like a function, so using round brackets var array = new Array("1.bmp","2.bmp");
An easier and probably more frequently used method is do it like this:
var array = ["1.bmp","2.bmp"];
So your whole code would be like this:
var images = new Array("1.bmp","2.bmp");
function changeImage(a) {
document.getElementById("image").src=a;
}
<P onclick="changeImage('1.bmp');">A1</P>
<P onclick="changeImage('2.bmp');">A2</P>
<P onclick="changeImage(images[0]);">B1</P>
<P onclick="changeImage(images[1]);">B2</P>
<P onclick="changeImage(images[0]);window.alert(images[0]);">C1</P>
<P onclick="changeImage(images[1]);window.alert(images[1]);">C2</P>
<P><img id="image" src="3.bmp"></P>
Upvotes: 1