Reputation: 29
I know this task can easily be solved by just adding "bild1", "bild2" and "bild3" to the onclick events, but I wanted to try and solve this with an array, but it doesn't seem to work.. What am I doing wrong? Can functions even be saved in an array?
Thanks in advance.
<html>
<body>
<img src="bild1.png">
<button onclick="meinArray[0]">Bild1</button>
<button onclick="meinArray[1]">Bild2</button>
<button onclick="meinArray[2]">Bild3</button>
<script>
let meinArray = new Array();
meinArray[0] = bild1();
meinArray[1] = bild2();
meinArray[2] = bild3();
<!-- let i = 0; -->
function bild1(){
document.images[0].src = "bild1.png";
}
function bild2(){
document.images[0].src = "bild2.png";
}
function bild3(){
document.images[0].src = "bild3.png";
}
</script>
</body>
</html>
Upvotes: 1
Views: 69
Reputation: 17570
You can convert to one function and store only values in array rather than writing lots of functions for every new images
function bild(index){ document.images[0].src = index; }
<img src="bild1.png">
<button onclick="bild('bild1.png')">Bild1</button>
<button onclick="bild('bild2.png')">Bild2</button>
<button onclick="bild('bild3.png')">Bild3</button>
Upvotes: 1
Reputation: 8817
You need to save a reference to a functions instead of executing them:
meinArray[0] = bild1;
meinArray[1] = bild2;
meinArray[2] = bild3;
and then execute them like:
<button onclick="meinArray[0]()">Bild1</button>
Upvotes: 1