【问题标题】:Add text from a variable to href link inside actor tag将变量中的文本添加到演员标签内的 href 链接
【发布时间】:2021-09-08 05:56:09
【问题描述】:

我有 15 个带有这样的 href 链接的演员标签

    <a href="https://www.w3schools.com/temp.pdf"></a>

由于这些 PDF 经常更新,我不想在浏览器中缓存它们,所以我想通过将 updateDate 存储在变量中,将更新日期添加为 ?date=updateDate

    <script>
        updateDate = "20210624";
    </script>

我想更新我的href 链接,因为它可能会在最后添加日期到网址

    <a href="https://www.w3schools.com/temp.pdf?date="+updateDate></a>

但它不起作用。我对此进行了研究,并知道我需要为 15 个链接中的每一个单独更新 url。有什么方法可以存储日期值并将其用于所有 15 个链接而不更改所有人?

【问题讨论】:

    标签: javascript html href


    【解决方案1】:

    试试这个:

    document.querySelectorAll('a').forEach(e => {
      e.href += new Date().getTime();
    })
    <a href='https://www.w3schools.com/temp.pdf?date='>link</a>
    <a href='https://www.w3schools.com/temp.pdf?date='>link</a>
    <a href='https://www.w3schools.com/temp.pdf?date='>link</a>

    如果您只想更改某些锚标记的href,请为它们分配一个类名:

    document.querySelectorAll('a.nocache').forEach(e => {
      e.href += new Date().getTime();
    })
    <a class="nocache" href='https://www.w3schools.com/temp.pdf?date='>link</a>
    <a href='https://www.w3schools.com/temp.pdf'>link</a>
    <a class="nocache" href='https://www.w3schools.com/temp.pdf?date='>link</a>

    【讨论】:

    • 如果我有一些其他 href 元素不想添加此日期怎么办?
    • @user147504 很高兴为您提供帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 2014-01-18
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    相关资源
    最近更新 更多