gpt4 book ai didi

javascript - 如何用JS选择动态创建的特定元素?

转载 作者:行者123 更新时间:2023-12-03 00:13:25 24 4
gpt4 key购买 nike

<div class="gallery-container">
<?php while (have_rows('gallery')): ?>
[...]
<div class="toggle-container">
<button class="toggle-button active" onclick="gridView()">Grid</button>
<button class="toggle-button" onclick="listView()">List</button>
</div>
<div class="gallery-items grid-items">
[...Gallery Items...]
</div>
<?php endwhile; ?>
</div>

当使用上面所示的 while 循环创建元素时,选择页面上特定元素的最佳方法是什么。这是一个不断增长的列表,也可以删除元素。

在此示例中,我生成一个充满小画廊的页面,以及每个画廊旁边的网格/ ListView 的切换按钮。

我试图让所有这些按钮仅与它们一起生成的图库一起使用。

我知道如何根据索引手动选择它们,但我不知道如何调整代码以使其能够单独与每个小画廊一起使用。

这是我想出的让它与第一个画廊一起使用的方法:

<script>
const button = document.getElementsByClassName('toggle-button');
const element = document.getElementsByClassName('gallery-items');

function listView() {
if ( element[0].classList.contains('grid-items') ){
element[0].classList.remove("grid-items");
}

button[0].classList.toggle('active');
button[1].classList.toggle('active');
}

function gridView() {
if ( !element[0].classList.contains('grid-items') ){
element[0].classList.add("grid-items");
}

button[0].classList.toggle('active');
button[1].classList.toggle('active');
}
</script>

最佳答案

您可以考虑改用事件委托(delegate):向 .gallery-container 添加点击监听器。如果单击的目标是 .toggle-button,则运行适当的逻辑,在单击时选择相关的周围元素:

document.querySelector('.gallery-container').addEventListener('click', ({ target }) => {
if (!target.matches('.toggle-button')) {
return;
}
const toggleContainer = target.parentElement;
const btns = toggleContainer.children;
if (target === btns[0]) {
btns[0].classList.add('active');
btns[1].classList.remove('active');
} else {
btns[0].classList.remove('active');
btns[1].classList.add('active');
}
const galleryItems = toggleContainer.nextElementSibling;
if (target === btns[0]) {
galleryItems.classList.add('grid-items');
} else {
galleryItems.classList.remove('grid-items');
}
});
.active {
background-color: yellow;
}
.grid-items {
background-color: red;
}
<div class="gallery-container">
<div class="toggle-container">
<button class="toggle-button active">Grid</button>
<button class="toggle-button">List</button>
</div>
<div class="gallery-items grid-items">
[...Gallery Items...]
</div>

<div class="toggle-container">
<button class="toggle-button active">Grid</button>
<button class="toggle-button">List</button>
</div>
<div class="gallery-items grid-items">
[...Gallery Items 2...]
</div>
</div>

请注意,在添加特定类之前,无需显式测试 classList.contains 是否包含该类(不过,这样做没有坏处,只是没有必要)。

关于javascript - 如何用JS选择动态创建的特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54620951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com