[英]Javascript: getElementsByClassName: how to get only parents
I have html like this:我有这样的html:
<div class="item">
<img class="item-image" src="${item.getImage()}"/>
<p>${item.getName()}</p>
</div>
and Javascript:和 Javascript:
var classname = document.getElementsByClassName("item");
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', (e) => {
addBorder(e.target);
});
};
function addBorder(item) {
if (item.tagName = 'DIV') {
item.style.border = "3px solid red";
}
}
When I click on item, it adds a red border.当我单击项目时,它会添加一个红色边框。 However if the click happened to touch the image or the paragraph, the red border is drawn around them.
但是,如果单击碰巧触摸图像或段落,则会在它们周围绘制红色边框。 I tried to prevent it by adding the if condition inside
addBorder
, but it didn't help.我试图通过在
addBorder
添加 if 条件来阻止它,但它没有帮助。 Is there a way to only make the parent div red-bordered, even if the click happened to land inside p
or img
?有没有办法只使父 div 带有红色边框,即使点击发生在
p
或img
?
Because item.tagName = 'DIV'
means: assigning DIV
to item.tagName
.因为
item.tagName = 'DIV'
意味着:将DIV
分配给item.tagName
。 So you just need to replace item.tagName = 'DIV'
with item.tagName === 'DIV'
for comparing.所以你只需要用
item.tagName === 'DIV'
替换item.tagName = 'DIV'
item.tagName === 'DIV'
进行比较。
if (item.tagName === 'DIV') {
item.style.border = "3px solid red";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.