问题描述
我在编码时遇到了问题。 我的桌子很大,有很多行。 我正在使用这段代码从该表中获取数据:
let tag1 = document.querySelector('body > div.l-global-width.l-container-primary > div > div.l-container-col2.box-userprofile > section > table > tbody > tr:nth-child(1) > td:nth-child(2)').innerText;
问题是,我需要从此表中获取此标签的ID。
<tr data-tag-id="7" role="row">
<td class="ord">1</td>
<td>Komedia</td>
<td class="number">2</td>
<td class="number">10</td>
<td class="number">131</td>
<td class="number" data-sort-value="7.44">7,44</td>
<td class="number" data-sort-value="7.21">7,21</td>
<td class="number" data-sort-value="34434">573h 54m</td>
</tr>
..您可能会猜到,我不知道该怎么做。我已经尝试了一些方法,但是没有一个对我有用,而且我经验不足,无法提出其他想法。
有人可以帮我解决吗?我感谢所有帮助。
解决方法
使用属性选择器[]
:
const ELS_tagId = document.querySelectorAll("tr[data-tag-id]");
这将为您提供所有<tr>
个元素,其中包含data-tag-id
个元素的集合。
要循环播放它们:
ELS_tagId.forEach(function(el) {
console.log(el.dataset.tagId); // among which you'll get also that "7"
});
PS:请注意,在JS tag-id
→tagId
中使用破折号HTML data- *标签作为camelCase