gpt4 book ai didi

javascript - 如何按类查找元素数并在悬停时计算?

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

这是我的代码:

let btns = document.querySelectorAll('button');

for (let i = 0; i < btns.length; i++) {
btns[i].onmouseover = (event) => {
document.querySelector(`#result`).innerHTML = document.querySelectorAll(`#wrapper .innerElemType${i+1}`).length
}
}
#wrapper {
width: 10rem;
background: yellow;
margin-bottom: 1rem;
}

#btn {
width: 10rem;
}

#result {
width: 100px;
height: 20px;
margin-top: 40px;
background: red;
border-radius: 8px;
text-align: center;
}
<div id="wrapper">
<div class="Type1">
<div class="Type1-1">
<div class="Type1-1-1"></div>
<div class="Type1-1-1"></div>
<div class="Type1-1-1"></div>
</div>
<div class="Type1-1">
<div class="Type1-1-2"></div>
<div class="Type1-1-2"></div>
</div>
</div>

<div class="Type2">
<div class="Type2-1">
<div class="Type2-1-1"></div>
<div class="Type2-1-1"></div>
<div class="Type2-1-1"></div>
<div class="Type2-1-1"></div>
<div class="Type2-1-1"></div>
</div>
<div class="Type2-1">
<div class="Type2-1-2"></div>
<div class="Type2-1-2"></div>
<div class="Type2-1-2"></div>
</div>
</div>

<div class="Type3">
<div class="Type3-1">
<div class="Type3-1-1"></div>
<div class="Type3-1-1"></div>
</div>
<div class="Type3-1">
<div class="Type3-1-2"></div>
<div class="Type3-1-2"></div>
<div class="Type3-1-2"></div>
</div>
</div>

<div class="Type4">
<div class="Type4-1">
<div class="Type4-1-1"></div>
<div class="Type4-1-1"></div>
</div>
<div class="Type4-1">
<div class="Type4-1-2"></div>
<div class="Type4-1-2"></div>
</div>
</div>


<button id="Type1">Type1</button>
<button id="Type2">Type2</button>
<button id="Type3">Type3</button>
<button id="Type4">Type3</button>
<button id="Type1-1">Type1-1</button>
<button id="Type2-1">Type2-1</button>
<button id="Type3-1">Type3-1</button>
<button id="Type4-1">Type4-1</button>
<button id="Type1-1-1">Type1-1-1</button>
<button id="Type2-1-1">Type2-1-1</button>
<button id="Type3-1-1">Type3-1-1</button>
<button id="Type4-1-1">Type4-1-1</button>
</div>


<div id="result">Type1 Result</div>

我有一棵树,主要的 div 有类 Type1、Type2、Type3、Type4。在主 div 中,我们有子类,在子类中,我们有子类。

如何通过将鼠标悬停在相关按钮上来获取相同类元素的数量?需要 javascript 帮助。

https://jsfiddle.net/739bL1a4/7/

最佳答案

您只需要更改您的 CSS 选择器以在 wrapper 中查找其类属性与您悬停的按钮的类属性相匹配的 div。

`#wrapper div[class="${btns[i].innerText}"]`

关于javascript - 如何按类查找元素数并在悬停时计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56200595/

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