[英]JavaScript: How to make images display at the click of a button?
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. 我有多个按钮(ID为'a','b',...),如果单击它们,它们应该在以下位置显示其对应的图像('a.JPG','b.JPG',...)网站上的固定点。
The idea is to listen for when a button is clicked and change the code inside the output to include its id. 这个想法是侦听单击按钮的时间,然后更改输出中的代码以包含其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: 此代码应在每次单击按钮时更改src,并根据按钮的ID更改图片:
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.如果没有
src
且未提供alt
属性,则不会显示该图像。
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. 获取所有按钮,并在其上附加一个
click
侦听器。 Create img
element on button
click and append it to the element with id
output. 单击
button
创建img
元素,并将其附加到具有id
输出的元素上。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.