gpt4 book ai didi

javascript - 单击以使用 Javascript/ES6 更改内部子项和其他部分

转载 作者:行者123 更新时间:2023-11-30 11:23:49 25 4
gpt4 key购买 nike

所以我用 Jquery 做了这个: Game Gallery

但是我需要在 Vanilla/ES6 中更改它,我一直在研究如何在点击时定位 parent 的 child 并找到索引 (.eq($(this).parent().index ()) 对于其他部分(在我的例子中是复制和图像部分):

我的试用是做一个 for 循环,例如:

  const mode = document.querySelectorAll('.gamegallery span');
for (let i = 0; i < mode.length; i++) {
mode[i].onclick = function() {
this.parentNode.classList.toggle('active');
};
}

但似乎我缺少让 parent 与图标保持同步的东西,因为它设置了 .active 但在所有图标上保持 .active 。我试过:

if {
this.parentNode.classList.add('active');
}
else {
this.parentNode.classList.remove('active');
}

哪个什么都不做...我还缺少其他东西吗?

最后还要更改一个不同的部分,例如我使用的内容/图像:

 $('.gamegallery .game-images img').eq($(this).parent().index()).addClass('active');
});

我基本上需要一次完成相同的功能。删除图标的 active - content-images parents。找到第一个对象,然后转到父级并转到每个索引(默认为第一个)。 node.parentNode.childNodes; 是我发现的一件事……我会不断更新。不是要求这样做,而是我添加的代码中缺少的更多内容。具体第一部分。来自 EcsMaScript/Modern Vanilla 新手。

最佳答案

与其遍历节点层次结构来搜索要切换的元素,不如通过指定目标来简化它。如果您点击的节点的索引与您的预期目标不匹配,这会派上用场。

Checkout this Fiddle for a Demo

您可以使用 data- HTML 属性。例如:data-target=".xbox"可以应用于您的 span.circle元素,因为这是您要添加点击监听器的内容。

<span class="circle" data-target=".xbox">

并在 data-target 中添加类到你的目标:

<div class="swiper-slide xbox"></div>

<img src=".." class="xbox">

单击时,您可以使用以下元素从元素中拉取目标:this.dataset并指定您要查找的内容。在本例中为:const target = this.dataset.target .

通过从数据集中找到目标的选择器,我们可以找到带有选择器的元素:

const targets = document.querySelectorAll('.swipe-slider'+target+', .game-images '+target');

一旦我们有了目标,我们就可以删除当前的 active来自目标邻居的类(class)。不过,在本例中,我只是将其从所有内容中删除。

document.querySelectorAll('.swiper-slide, .game-images img').forEach(el => el.classList.remove('active'));

然后我们添加事件类:

targets.forEach(target => target.classList.add('active');

现在:

function handleClick(e) {

const target = this.dataset.target;
const targets = document.querySelectorAll('.swiper-slide'+target+', .game-images '+target);

document.querySelectorAll('.swiper-slide, .game-images img').forEach(el => el.classList.remove('active'));

targets.forEach(target => target.classList.add('active'));

}

关于javascript - 单击以使用 Javascript/ES6 更改内部子项和其他部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48794197/

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