我如何使我的手风琴/折叠工作与事件委托?



我想在我的网店的购物车抽屉里创建一个手风琴,但是我找不到解决这个问题的方法。

这里发生的事情是,我得到了元素,但一旦抽屉被重新渲染,那么我的引用就丢失了。因为DOM是动态变化的,所以我不应该这样做。相反,我应该使用事件委托,这样即使重新渲染,我的代码仍然可以工作。

var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
}
<button type="button" class="accordion">Expand me</button>
<div class="panel">
<p>Text here...</p>
</div>

有一个附加侦听器的accordion容器元素。然后在每个面板div中缓存div。使用类指定每个面板的信息是否应该可见。最初我们将它们都设置为display: none

const accordion = document.querySelector('.accordion');
const add = document.querySelector('.add');
accordion.addEventListener('click', handleClick, false);
add.addEventListener('click', handleAdd, false);
function handleAdd() {
const html = '<div class="panel"><button>Expand me: newPanel</button><div><p>New Panel</p></div></div>';
accordion.insertAdjacentHTML('beforeend', html);
}
function handleClick(e) {
const button = e.target;
// Check to see if the element we clicked on was
// the button
if (button.nodeName === 'BUTTON') {
// Find the closest panel ancestor
const parent = button.closest('.panel');
// Get all of the panels, even the ones newly added
const panels = accordion.querySelectorAll('.panel div');
// Remove all the `show` classes from the panels
panels.forEach(panel => panel.classList.remove('show'));
// And add `show` to the panels `div` which we previous hid
parent.querySelector('div').classList.add('show');
}
}
.panel div { display: none; }
.panel div.show { display: block; }
.add { margin-top: 1em; background-color: #44aa77; }
<div class="accordion">
<div class="panel">
<button>Expand me: one</button>
<div><p>One</p></div>
</div>
<div class="panel">
<button>Expand me: two</button>
<div><p>Two</p></div>
</div>
<div class="panel">
<button>Expand me: three</button>
<div><p>Three</p></div>
</div>
</div>
<button class="add">Add new panel</button>

最新更新