如何在Click事件中获取子元素 [英] How to get child element in a Click Event
本文介绍了如何在Click事件中获取子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要向一个Button添加一个Click事件,我需要获取此Button的父级,然后需要获取此父级的特定子级.
I'm adding a Click Event to a Button and I need to get the parent of this Button and after that I need to get a specific child of this parent.
问题还在于,我有多个这些按钮及其对应的容器和子项.
The issue also is that I have multiple of these buttons with its correspondant containers and childs.
我能够为每个按钮添加一个Click Event,但是我似乎无法独立获取这些按钮的元素.
I was able to add a Click Event for each button but i can't seem to get the elements of these buttons independently.
HTML
<div class="parentContainer">
<div class="otherElement"></div>
<a class="button">
<div class="childElement"></div>
</div>
JS
var btn = document.querySelectorAll(".button");
for (let i = 0; i < button.length; i++){
button[i].addEventListener('click', function(){
var container = this.closest('.parentContainer');
var j = 0;
for(j = 0; j < container.length; j++){
if(j.classList.contains('childElement')){
j.classList.add('Example')
} else {
container.style.background = "white";
}
};
});
}
对于单击的特定按钮,其兄弟元素(childElement)应获得示例"类.
For the specific button clicked, its brother element (childElement) should get a class of "Example".
推荐答案
您可以简化一些操作
// check if there is at least one .button (this prevents javascript errors)
if (document.querySelector('.button')) {
// select all buttons, each as el
document.querySelectorAll('.button').forEach(function(el) {
// bind click event to each el
el.addEventListener('click', function (e) {
// check also if there is at least on .childelement
// e.target is the clicked element, parentNode the parent, from there find .childElement
if (e.target.parentNode.querySelector('.childElement')) {
e.target.parentNode.querySelector('.childElement').classList.add('Example');
}
else {
e.target.parentNode.style.background = 'white';
}
});
});
}
<div class="parentContainer">
<div class="otherElement">otherElement</div>
<a class="button">button</a>
<div class="childElement">childElement</div>
</div>
这篇关于如何在Click事件中获取子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文