[英]Find a DOM Element using an attribute-value which is acquired dynamically?
已经有关于使用属性值获取 dom 元素的问题。 但是我的不一样,因为我的属性值是事先不知道的。
<div class='gameBoard'>
<div class="grid" index='0'></div>
<div class="grid" index='1'></div>
<div class="grid" index='2'></div>
<div class="grid" index='3'></div>
<!-- Goes up to 100 div / 99 index values -->
</div>
我有一个 div 游戏板代表一个包含 100 个 div 的 dom 元素,每个元素的索引值从 0 到 99。下面我循环遍历所有 div,当鼠标悬停在一个 div 上时,我得到它的索引(数据属性) . (如果方向在 x 轴上,那么我会这样做)
const one = el;
const onei = el.getAttribute('index');
const two = el.nextElementSibling;
const twoi = two.getAttribute('index');
但是当方向在 y 轴上时,我不需要下一个 div 元素,而是下面的那个。 例如:如果索引为 0,我需要 0 + 10 = 10,所以我需要索引为 10 的 div。我尝试了下面的代码但它不起作用因为值是动态检索的,我尝试使用字符串插值但它没有工作。 所以请帮助!
const grids = document.querySelectorAll('.grid');
el.addEventListener('mouseover', (e) => {
if (foo === 'destroyer' || foo === 'submarine') {
if (currentDirection === 'Y') {
const one = el;
const onei = Number(el.getAttribute('index'));
const twoi = onei + 10;
const two = document.querySelector("[index='twoi']");
console.log(two, twoi);
}
}
});
querySelector 中的字符串连接错误
它应该与该行的以下代码一起使用
const two = document.querySelector(`[index="${twoi}"]`);
您的问题是字符串插值。 您实际上是在寻找具有索引twoi
的元素。 相反,尝试用反引号插入字符串,例如
const two = document.querySelector(`[index='${twoi}]'`);
或者只是将 twoi 字符串添加到其中:
const two = document.querySelector("[index=" + twoi + "]");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.