javascript - 使用 jQuery/Javascript 从 ID 更新 href
问题描述
我正在尝试使用 jQuery/Javascript 向我的 href 添加一个 id:
这是我的 HTML:
<a href="product#=" id="39">Test</a>
我想要实现的是:
<a href="product#=39" id="39">Test</a>
基本上就是想把这个ID加到href中,
到目前为止,设法做到这一点:
var link = $('a');
link.attr('href', link.attr('href') + '39');
这没关系,但如果我有更多链接,这将不起作用,因为该值是硬编码的,
任何人都可以尝试帮助我解决这个问题
解决方案
您可以使用forEach
循环锚点:
window.addEventListener('load', function() {
const anchors = document.querySelectorAll('a')
anchors.forEach(a => {
a.href = a.getAttribute("href") + a.id;
console.log(a.getAttribute("href"))
})
})
<a href="product#=" id="39">Test</a>
<a href="product#=" id="40">Test</a>
<a href="product#=" id="41">Test</a>
推荐阅读
- python - 如何将命令输出存储在文件中
- django - 如何使用通用类视图在 Django 中过滤类别明智的产品
- algorithm - 从 n 个数字的数组中选择 P 个独立对,最小化对的绝对差之和
- javascript - 如何在 Firestore 中迁移文档?
- python - Parsing dates from OCRed files using dateparser library
- php - 如何通过localhost打开php文件?
- ios - 未加载库:@rpath/FBSDKCoreKit.framework/FBSDKCoreKit
- python - 使用 Gstreamer 在一段时间内停止读取 hls 流
- c - 原始蓝牙套接字,中止连接调用并正常关闭?
- php - php preg_match_all 获取第二个选择框选项