首页 > 解决方案 > 使用 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');

这没关系,但如果我有更多链接,这将不起作用,因为该值是硬编码的,

任何人都可以尝试帮助我解决这个问题

标签: javascriptjquery

解决方案


您可以使用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>


推荐阅读