已經存在關于使用屬性值獲取 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);
}
}
});
uj5u.com熱心網友回復:
querySelector 中的字串連接錯誤
它應該使用該行的以下代碼
const two = document.querySelector(`[index="${twoi}"]`);
uj5u.com熱心網友回復:
你的問題是字串插值。您實際上是在尋找具有 index 的元素twoi。相反,嘗試用反引號插入字串,例如
const two = document.querySelector(`[index='${twoi}]'`);
或者只是將 twoi 字串添加到它:
const two = document.querySelector("[index=" twoi "]");
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/452212.html
標籤:javascript html dom 事件处理 dom 事件
