英文:
how could i change this java script or copy it to have two on click function for two buttons and images
问题
html:
<div class="vaultcontainer">
<img src="img/vault.svg" alt="" id="image">
</div>
<button id="image-button">click </button>
<button id="image-button2">click </button>
js:
const button = document.getElementById('image-button');
const image = document.getElementById('image');
button.addEventListener('click', function() {
changeImage();
});
function changeImage() {
image.src = 'img/vault2.svg';
}
英文:
html:
<div class="vaultcontainer">
<img src="img/vault.svg" alt="" id="image">
</div>
<button id="image-button">click </button>
<button id="image-button2">click </button>
js:
const button = document.getElementById('image-button');
const image = document.getElementById('image');
button.addEventListener('click', function() {
changeImage();
});
function changeImage() {
image.src = 'img/vault2.svg';
}
答案1
得分: 1
Sure, here's the translated content:
使用一个类:
<button class="js-changeImage">点击 </button>
<button class="js-changeImage">点击 </button>
然后,在JS中使用 querySelectorAll()
和返回的NodeList上的 .forEach()
:
const buttons = document.querySelectorAll('js-changeImage');
buttons.forEach(btn => btn.addEventListener('click', changeImage));
如果您需要为按钮指定不同的图像,请使用 data-* 属性:
<img src="img/vault.svg" alt="" id="image">
<button data-image="img/cat.svg">点击 </button>
<button data-image="img/dog.svg">点击 </button>
const image = document.querySelector('#image');
const buttons = document.querySelectorAll('[data-image]');
buttons.forEach(btn => btn.addEventListener('click', () => {
changeImage(btn.dataset.image);
});
function changeImage(src) {
image.src = src;
}
英文:
Use a class:
<button class="js-changeImage">click </button>
<button class="js-changeImage">click </button>
then, in JS use querySelectorAll()
and .forEach()
on the returned NodeList:
const buttons = document.querySelectorAll('js-changeImage');
buttons.forEach(btn => btn.addEventListener('click', changeImage));
If you need to specify different images for your buttons — use the data-* attribute:
<img src="img/vault.svg" alt="" id="image">
<button data-image="img/cat.svg">click </button>
<button data-image="img/dog.svg">click </button>
const image = document.querySelector('#image');
const buttons = document.querySelectorAll('[data-image]');
buttons.forEach(btn => btn.addEventListener('click', () => {
changeImage(btn.dataset.image);
});
function changeImage(src) {
image.src = src;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论