提问人:Sonoran Studios 提问时间:12/10/2022 更新时间:12/10/2022 访问量:29
在 DOM 遍历中苦苦挣扎。如何选择“#img”元素?
Struggling with DOM traversing. How can I select the "#img" element?
问:
我正在尝试使用 for 循环将事件侦听器附加到多个按钮。事件功能将通过隐藏正面来“翻转”我的卡片。
<div class="team__box">
<div class="front" id="front">
<img
src="/assets/avatar-drake.jpg"
alt="headshot"
class="front__img"
/>
<h3 class="front__name">Drake Heaton</h3>
<p class="front__info">Business Development Lead</p>
</div>
<div class="back hide" id="back">
<h3 class="back__name">Drake Heaton</h3>
<p class="back__quote">
“Hiring similar people from similar backgrounds is a surefire way
to stunt innovation.”
</p>
<div class="back__social">
<a href="#" class="back__social-link"
><img
src="/assets/icon-twitter.svg"
alt="twitter"
class="back__social-img"
/></a>
<a href="#" class="back__social-link"
><img
src="/assets/icon-linkedin.svg"
alt="linkedin"
class="back__social-img"
/></a>
</div>
</div>
<button class="team__btn front__btn" id="btn">
<img
src="/assets/icon-cross.svg"
alt="close button"
class="btn__img"
id="img"
/>
</button>
</div>
<div class="team__box">
<div class="front" id="front">
<img
src="/assets/avatar-griffin.jpg"
alt="headshot"
class="front__img"
/>
<h3 class="front__name">Griffin Wise</h3>
<p class="front__info">Lead Marketing</p>
</div>
<div class="back hide" id="back">
<h3 class="back__name">Griffin Wise</h3>
<p class="back__quote">
“Unique perspectives shape unique products, which is what you need
to survive these days.”
</p>
<div class="back__social">
<a href="#" class="back__social-link"
><img
src="/assets/icon-twitter.svg"
alt="twitter"
class="back__social-img"
/></a>
<a href="#" class="back__social-link"
><img
src="/assets/icon-linkedin.svg"
alt="linkedin"
class="back__social-img"
/></a>
</div>
</div>
<button class="team__btn front__btn" id="btn">
<img
src="/assets/icon-cross.svg"
alt="close button"
class="btn__img"
id="img"
/>
</button>
</div>
下面的 Javascript。它几乎都在工作,除了当我直接单击“#img”元素时。我假设
const btn = document.getElementsByClassName("team__btn");
for (i = 0; i < btn.length; i++) {
btn[i].addEventListener("click", function (e) {
console.log(e.target);
let front = e.target.closest("div").firstElementChild;
let back = e.target.closest("div").children[1];
if (e.target !== "img") {
img = e.target.firstElementChild;
} else {
img = e.target;
}
front.classList.toggle("hide");
back.classList.toggle("hide");
if (front.classList.contains("hide")) {
img.src = "./assets/icon-close.svg";
} else {
img.src = "./assets/icon-cross.svg";
}
});
}
假设我直接单击“#img”元素,我尝试通过 if/else 语句将该目标元素分配给 img 变量。使用它,我希望能够重新分配 img 变量的 src 属性,具体取决于卡的正面或背面是隐藏的。
但是,当我直接单击img元素时,我收到以下错误: “未捕获的 TypeError:无法设置 null 属性(设置 'src') 在 HTMLButtonElement。
什么给了?
答: 暂无答案
评论