gpt4 book ai didi

javascript - 使用 Vanilla JavaScript 将父类别文本和 URL 保存到变量中

转载 作者:行者123 更新时间:2023-12-02 20:53:19 25 4
gpt4 key购买 nike

我想将父类别文本和 URL 保存到变量中。在下面的示例中,它是击球手套。

这是 HTML。

<section class="breadcrumbs">
<ul>
<li>
<a href="/store" title="" class="crumb" style="display: none;">Home</a>
</li>
<li>
<a href="/store/browse/sports/_/N-84a" class="crumb ">Sports</a>
</li>
<li>
<a href="/store/browse/sports/baseballsoftball/_/N-apf" class="crumb ">Baseball/Softball</a>
</li>
<li>
<a href="/store/browse/sports/baseballsoftball/_/N-apm" class="crumb ">Batting Gloves</a>
</li>
<li class="crumb"><font color="#6e6e6e"> Nike Hyperdiamond Edge Girls' Batting Gloves</font></li>
</ul>
</section>

在上面的例子中,变量是:

pc = 'batting gloves'
pcURL = '/store/browse/sports/baseballsoftball/_/N-apm'

Javascript:

我不知道如何写这个。

最佳答案

你可以查看我的解决方案。希望这会有所帮助。

我用过.getAttribute('href');.innerHTML 获取这些值

const crumbItems = document.querySelectorAll('li a.crumb');
const battingGlovesItem = crumbItems[crumbItems.length - 1];

const pc = battingGlovesItem.innerHTML;
const pcURL = battingGlovesItem.getAttribute('href');

console.log(`pc: ${pc},\npcURL: ${pcURL}`)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<section class="breadcrumbs">
<ul>
<li>
<a href="/store" title="" class="crumb" style="display: none;">Home</a>
</li>
<li>
<a href="/store/browse/sports/_/N-84a" class="crumb ">Sports</a>
</li>
<li>
<a href="/store/browse/sports/baseballsoftball/_/N-apf" class="crumb ">Baseball/Softball</a>
</li>
<li>
<a href="/store/browse/sports/baseballsoftball/_/N-apm" class="crumb ">Batting Gloves</a>
</li>
<li class="crumb"><font color="#6e6e6e"> Nike Hyperdiamond Edge Girls' Batting Gloves</font></li>
</ul>
</section>
</body>
</html>

关于javascript - 使用 Vanilla JavaScript 将父类别文本和 URL 保存到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61551349/

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