在下面的示例中,如何通用地将描述详细信息 <dd>
定位在其描述术语 <dt>
之下,并在目标{ {1}}和<dd>
,而不使用ID。
<button>
document.addEventListener('DOMContentLoaded', function() {
[].forEach.call(document.querySelectorAll('button'), function(el) {
el.addEventListener('click', function(e) {
if (e.target.nodeName.toLowerCase() == 'a') {
e.preventDefault();
}
e.target.classList.toggle('active');
});
});
document.getElementById('expand-aluminum').addEventListener('click', function(e) {
if (e.target.nodeName.toLowerCase() == 'a') {
e.preventDefault();
}
document.getElementById('aluminum-definition').classList.toggle('open');
});
document.getElementById('expand-silver').addEventListener('click', function(e) {
if (e.target.nodeName.toLowerCase() == 'a') {
e.preventDefault();
}
document.getElementById('silver-definition').classList.toggle('open');
});
document.getElementById('expand-gold').addEventListener('click', function(e) {
if (e.target.nodeName.toLowerCase() == 'a') {
e.preventDefault();
}
document.getElementById('gold-definition').classList.toggle('open');
});
document.getElementById('expand-platinum').addEventListener('click', function(e) {
if (e.target.nodeName.toLowerCase() == 'a') {
e.preventDefault();
}
document.getElementById('platinum-definition').classList.toggle('open');
});
});
dd { visibility: hidden }
.open { visibility: visible }
.active { color: blue }
答案 0 :(得分:2)
您可以使用事件委托代替向多个事件监听器添加事件,并向[1, 5, 6, 8, 9, 52, 74, 91]
-1
3
添加一个单个事件监听器。如果单击的元素是dl
,则导航到按钮的父元素(button
)并访问其dt
以转到关联的nextElementSibling
:>
dd
document.querySelector('dl').addEventListener('click', ({ target }) => {
if (!target.matches('button')) return;
target.classList.toggle('active');
target.parentElement.nextElementSibling.classList.toggle('open');
});
dd {
visibility: hidden
}
.open {
visibility: visible
}
.active {
color: blue
}
abbr {
pointer-events: none
}