选择国家代码时,图片未定义,问题很可能是在js中,但我不确定,请帮助。
let header = document.querySelectorAll('.select__header')
let item = document.querySelectorAll('.select__item')
let select = document.querySelector('.select')
let images = document.querySelectorAll('.select__item img')
header.forEach(i => {
i.addEventListener('click', () => {
i.parentElement.classList.toggle('active')
})
})
item.forEach(i => {
i.addEventListener('click', () => {
images.forEach(el => {
let text = images[el] + i.textContent,
currentText = select.querySelector('.select__current')
currentText.innerText = text
select.classList.remove('active')
console.log(images);
})
})
})
.select {
width: 110px;
position: relative;
}
.select img {
width: 30px;
}
.select__header {
border: 1px solid #ccc;
cursor: pointer;
display: flex;
}
.select__current {
font-size: 18px;
padding: 8px;
}
.select__icon {
display: flex;
justify-content: center;
align-items: center;
flex-shrink: 0;
height: 40px;
width: 15px;
margin-left: auto;
}
.select__icon img {
width: 10px;
}
.select__body {
display: none;
left: 0;
right: 0;
border: 1px solid #ccc;
position: absolute;
top: 100%;
background-color: #fff;
}
.select__item {
line-height: 24px;
padding: 8px;
font-size: 16px;
cursor: pointer;
}
.select__item:hover {
background-color: #ccc;
}
.select.active .select__body {
display: block;
}
<div class="select">
<div class="select__header">
<span class="select__current"> <img src="./img/rus.jpg" alt=""> +7</span>
<span class="select__icon"><img src="./img/Stroke.svg" alt=""></span>
</div>
<div class="select__body">
<div class="select__item"><img src="./img/rus.jpg" alt="">+7</div>
<div class="select__item"><img src="./img/usa.jpg" alt="">+1</div>
<div class="select__item"><img src="./img/Flag_of_Turkey.svg.webp" alt="">+90</div>
</div>
</div>
我认为这里的问题:
let text = images[el] + i.textContent
我想在选择国家时显示国家代码的图像。但不幸的是没能成功。
3条答案
按热度按时间dgtucam11#
item和images是两个不同的数组,你在没有明确含义的项目中嵌套了图像。不需要准备所有图像的数组。对于每个项目,您可以使用以下代码找到图像:
bihw5rsg2#
})
vwoqyblh3#
授权和简化