I have multiple buttons (with the ids 'a', 'b', ...) and if you click them, they should display their corresponding image ('a.JPG', 'b.JPG', ...) at a fixed point on the website.
The idea is to listen for when a button is clicked and change the code inside the output to include its id.
'use strict';
var bild = '', i, j, k;
function gedrueckt(k) {
bild = '<img src="img/' + k + '.JPG" width="1600" hight="900" alt="Vergroessertes Bild"></img>';
document.querySelector('output').innerHTML = bild;
}
for (i = 1; i < 8; i = i + 1) {
j = String.fromCharCode(97 + i);
document.getElementById(j).addEventListener('click', gedrueckt(j));
}
The problem is that an image already appears before any button is clicked and pressing a different button does not change the displayed image.
This code should change the src on each button click, changing the picture according the the ID of the button:
let img = document.getElementById('img') const change = id => { img.src = `${id}.jpeg` img.alt = `${id}.jpeg` }
<img id="img" src=""> <br> <button onclick="change(this.id)" id="a">A</button> <button onclick="change(this.id)" id="b">B</button> <button onclick="change(this.id)" id="c">C</button>
If there no
src
and noalt
property provided, the image will not be displayed.
I might've misunderstood you, in that you want the image to change on keyboard button press, which this code should do the trick:
let img = document.getElementById('img') const change = id => { img.src = `${id}.jpeg` img.alt = `${id}.jpeg` } const list = ['a','b','c'] document.addEventListener('keydown', e => list.includes(e.key) && change(e.key))
<img id="img" src="">
Get all the buttons and attach an click
listener to it. Create img
element on button
click and append it to the element with id
output.
const buttons = document.querySelectorAll('button') const output = document.querySelector('#output'); buttons.forEach((button) => { button.addEventListener('click', function() { const img = document.createElement('img'); img.src = this.id + '.jpg'; output.innerHTML = ""; output.appendChild(img); }); });
<button id="a">one</button> <button id="b">two</button> <button id="c">three</button> <div id="output"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.