我正在嘗試查找特定類 (findMe) 的下一個實體的 ID(test1、test2、test3 等)。
這是我的代碼:HTML:
<div class="container">
<table>
<tr id="test1" class="findMe">
<td>
<button class="next">Next</button>
</td>
</tr>
<tr id="test2" class="findMe">
<td>
<button class="next">Next</button>
</td>
</tr>
</table>
<div id="test3" class="findMe">
</div>
</container>
JS:
$(".next").click(function() {
console.log($(this).parent().closest(".findMe").next().attr('id'));
})
我可以找到 ID“test2”但找不到“test3”。為什么?
uj5u.com熱心網友回復:
第二個.findMe與第三個最近的祖先.findMe是祖父母,而不是父母。(<tr>在 a 內<tbody>。)
雖然您可以通過使動態 DOM 導航更靈活來修復它(有點),但我認為更簡單的方法是選擇所有.findMes,然后訪問下一個索引。
const findMes = $('.findMe');
const thisIndex = findMes.index(this);
console.log(findMes[thisIndex 1]?.id);
您還可以使用getElementsByClassName, 其集合是實時的,而不是每次都重新選擇所有元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/385757.html
標籤:javascript html 查询
