gpt4 book ai didi

javascript - 获取可用的 href

转载 作者:行者123 更新时间:2023-12-03 01:27:00 25 4
gpt4 key购买 nike

我正在尝试从 tr-td 列表中获取 href 数据(请参阅示例代码)。但它总是返回 null 值。我尝试过使用 .getElementby...() 的其他方法,但我总是在某处撞墙。

<!DOCTYPE html>
<html>
<body>
<p>Click the button to see the 2 results in an alerte box.</p>
<button onclick="myFunction()">Try it</button>
<table class="list" role="presentation">
<thead>
<tr>
<th><a href="/Parliamentarians/fr/constituencies?sortBy=Name&sortDescending=True">Circonscription</a><span class="icon-ascending"></span></th>
<th><a href="/Parliamentarians/fr/constituencies?sortBy=Province&sortDescending=False">Province / Territoire</a></th>
</tr>
</thead>
<tbody>
<tr>
<td class="constituency">
<a title="Cliquez pour acc&#233;der au profil de la circonscription" href="/Parliamentarians/fr/constituencies/Abbotsford(898)">Abbotsford</a>
</td>
<td class="constituency">Colombie-Britannique</td>
<td class="personName">
<a title="Cliquez pour acc&#233;der au profil du d&#233;put&#233;" href="/Parliamentarians/fr/members/Ed-Fast(35904)">Fast, Ed <abbr>(L'hon.)</abbr></a>
</td>
<td class="caucus">
<a target="_blank" title="Site Web du parti politique - Ouvre une nouvelle fen&#234;tre" href="http://www.conservateur.ca">Conservateur</a>
</td>
</tr>
<tr>
<td class="constituency">
<a title="Cliquez pour acc&#233;der au profil de la circonscription" href="/Parliamentarians/fr/constituencies/Abitibi-Baie-James-Nunavik-Eeyou(637)">Abitibi—Baie-James—Nunavik—Eeyou</a>
</td>
<td class="constituency">Qu&#233;bec</td>
<td class="personName">
</td>
<td class="caucus">
</td>
</tr>
</tbody>
</table>
<script>
function myFunction() {
var nodeList = document.querySelectorAll('.constituency');
var nodeList2 = document.querySelectorAll('.personName');
var nodeList3 = document.getElementsByClassName('caucus');

/* i+=2, because first is circonscription and next is province */
for (var i = 0, j = 0; i < nodeList.length; i += 2, j++) {
alert(nodeList[i].innerText + '|' + nodeList[i].getAttribute('href') + '|' + nodeList[i + 1].innerText + '|' + nodeList2[j].innerText + '|' + nodeList2[j].getAttribute('href') + '|' + nodeList3[j].innerText + '|' + nodeList3[j].getAttributeNode('href'));
}
}
</script>
</body>
</html>

谢谢。

最佳答案

href 是“a”标签的属性,而您的代码希望在 td/tr 上找到它。您在循环中又错过了更深入的一层。

<td class="constituency">
<!-- note the href on the a tag -->
<a title="Cliquez pour acc&#233;der au profil de la circonscription" href="/Parliamentarians/fr/constituencies/Abbotsford(898)">Abbotsford</a>
</td>

您的 JavaScript 代码应如下所示:

 nodeList[i].children[0].getAttribute('href')

关于javascript - 获取可用的 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51487102/

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