[英]Click to change image across multiple items
I'm trying to set up a javascript function that will take a down arrow image and swap it with an up arrow image when clicked.我正在尝试设置一个javascript函数,该函数将获取向下箭头图像并在单击时将其与向上箭头图像交换。 It worked when the image had an id, but because I have a couple menu items that uses the arrow image, I wanted to try to get it to work as a class name or just regular name, but I can't get the function to change the source of the image when it's not an id.
当图像有 id 时它可以工作,但是因为我有几个使用箭头图像的菜单项,我想尝试让它作为类名或普通名称工作,但我无法获得函数当图像不是 id 时更改图像的来源。 Can anyone help?
任何人都可以帮忙吗? Here is my current HTML markup:
这是我当前的 HTML 标记:
<div class="header__links hide-for-mobile" >
<a id="subMenu" href="#">Features <img class="downArrow" src="/assets/images/icon-arrow-down.svg"></a>
<a href="#">Company</a>
<a href="#">Careers</a>
<a href="#">About</a>
</div>
And here is my JS这是我的 JS
const subMenu = document.querySelector('#subMenu');
subMenu.addEventListener('click', function() {
if(subMenu.classList.contains('subOpen')) {
subMenu.classList.remove('subOpen');
document.getElementsByClassName('downArrow').src="/assets/images/icon-arrow-down.svg";
}
else {
subMenu.classList.add('subOpen');
document.getElementsByClassName('downArrow').src="/assets/images/icon-arrow-up.svg";
}
})
Right now since your markup only contains a single element with the downArrow
class you could update your code to:现在,由于您的标记仅包含一个带有
downArrow
类的元素,您可以将代码更新为:
const subMenu = document.querySelector('#subMenu');
subMenu.addEventListener('click', function() {
if(subMenu.classList.contains('subOpen')) {
subMenu.classList.remove('subOpen');
document.getElementsByClassName('downArrow')[0].src="/assets/images/icon-arrow-down.svg";
}
else {
subMenu.classList.add('subOpen');
document.getElementsByClassName('downArrow')[0].src="/assets/images/icon-arrow-up.svg";
}
})
But a better way to do this would be to loop through the results of the getELementsByClassName
method.但更好的方法是
getELementsByClassName
方法的结果。 You could do that with something like:你可以这样做:
const subMenu = document.querySelector('#subMenu');
subMenu.addEventListener('click', function() {
if(subMenu.classList.contains('subOpen')) {
subMenu.classList.remove('subOpen');
Array.from(document.getElementsByClassName("downArrow")).forEach(
function(element, index, array) {
element.src="/assets/images/icon-arrow-down.svg";
}
);
}
else {
subMenu.classList.add('subOpen');
Array.from(document.getElementsByClassName("downArrow")).forEach(
function(element, index, array) {
element.src="/assets/images/icon-arrow-up.svg";
}
);
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.