gpt4 book ai didi

javascript - 循环遍历 html 元素数组,并为指定的元素指定一个类,其余的为另一个类

转载 作者:行者123 更新时间:2023-12-03 02:18:58 24 4
gpt4 key购买 nike

这可能是一个愚蠢的问题,但我有一个名为 selectFace(face);

的函数

基本上,我希望该函数执行的操作是在单击的项目上添加一个类,然后所有其他项目获得另一个类

我现在得到的是

HTML

<div class="tool_faces">
<div (click)="selectFace('very-unhappy', 1, $event)" class="tool_faces_circle tool_faces_circle--very-unhappy">
<img class="very-unhappy" src="../../../../../assets/Images/wellness-faces/very-unhappy.svg" alt="very-unhappy face">
</div>
<div (click)="selectFace('unhappy', 2, $event)" class="tool_faces_circle tool_faces_circle--unhappy">
<img class="unhappy" src="../../../../../assets/Images/wellness-faces/unhappy.svg" alt="unhappy face">
</div>
<div (click)="selectFace('okay', 3, $event)" class="tool_faces_circle tool_faces_circle--okay">
<img class="okay" src="../../../../../assets/Images/wellness-faces/okay.svg" alt="okay face">
</div>
<div (click)="selectFace('happy', 4, $event)" class="tool_faces_circle tool_faces_circle--happy">
<img class="happy" src="../../../../../assets/Images/wellness-faces/happy.svg" alt="happy face">
</div>
<div (click)="selectFace('super-happy', 5, $event)"class="tool_faces_circle tool_faces_circle--super-happy">
<img class="super-happy" src="../../../../../assets/Images/wellness-faces/super-happy.svg" alt="super-happy face">
</div>
</div>

typescript

selectFace(face, number, event) {
const nodeList = document.querySelectorAll('.tool_faces_circle');
const facesArray = Array.from(nodeList);
this.selectedFace = number;
facesArray.forEach(function(item){
item.classList.remove('tool_select');
item.classList.add('tool_unselect');
});
let getTargetEvent = event.target;
getTargetEvent.classList.add('tool_select');
}

因此,当您单击 div .tool_faces_circle 时,它应该添加一个名为 .tool_selected 的类,并为 tool_faces div 中的每个其他面获取一个名为 .tool_unselect

的类

但我无法让它工作..我不确定我做错了什么..

如有任何帮助,我们将不胜感激!

谢谢

最佳答案

这就是答案

selectFace(face, number, event) {
const nodeList = document.querySelectorAll('.tool_faces_circle');
var facesArray = Array.from(nodeList);
this.selectedFace = number;
facesArray.forEach(function(item){
item.classList.remove('tool_select');
item.classList.add('tool_unselect');
});

facesArray[number].classList.remove('tool_unselect');
facesArray[number].classList.add('tool_select');

let getTargetEvent = event.target;
// getTargetEvent.classList.add('tool_select');
}

关于javascript - 循环遍历 html 元素数组,并为指定的元素指定一个类,其余的为另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49248229/

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