【问题标题】:How to change multiple meta tag descriptions with a single variable (vanilla JS)?如何使用单个变量(vanilla JS)更改多个元标记描述?
【发布时间】:2021-12-11 07:09:07
【问题描述】:

我的网站上有以下元标记:

<meta name="description" content="content here" />
<meta itemprop="description" content="content here">
<meta property="og:description" content="content here" />

这三个元属性在我的网站上都是必需的。但是,有没有办法引用 JS 变量中的单个描述,我可以将其传递给这些内容属性中的每一个?

【问题讨论】:

标签: javascript meta-tags


【解决方案1】:

您可以将 querySelector 与 meta[key=value] 一起使用,然后使用 setAttribute(key,value) 设置 Attribute。

document.querySelector("meta[name='description'" ).setAttribute("content", "some new meta description");

document.querySelector("meta[itemprop='description'" ).setAttribute("content", "some new meta description");

document.querySelector("meta[property='description'" ).setAttribute("content", "some new meta description");

【讨论】:

  • 这个问题是我仍在三个不同的地方添加描述。这一次,我不是在单独的元标记中添加描述哦,而是在单独的 JavaScript 变量中添加描述
  • @Millhorn 您可以将选择器放入一个数组并对其进行迭代。 selectors = [ 'meta[name="description"]', 'itemprop="description"', 'property="og:description"' ]; const content = 'some content'; selectors.forEach((sel) =&gt; { let meta = document.querySelector( sel ) meta.setAttribute("content", content) })
  • 我试过了,但是没有用。
  • @Millhorn 您在控制台中遇到错误?你能分享一下错误吗?
  • 我没有收到控制台错误。当我检查页面的源代码时,它只是没有生成任何元数据。
【解决方案2】:

这是一个简单的方法

<meta class="meta" name="description" content="content here" />
<meta class="meta" itemprop="description" content="content here">
<meta class="meta" property="og:description" content="content here" />
<script>
    document.querySelectorAll(".meta").forEach((el) => {
        el.setAttribute("content", "your content");
    })
</script>

【讨论】:

  • 这个我试过了,没用。
  • @Millhorn,经过测试,我的代码能够成功更新每个元标记,使其具有您放置的任何内容的内容属性来代替“您的内容”。你是如何测试它的?结果如何?
  • 好奇...您是在使用 Chrome、FF 还是 Edge 进行测试?
  • 我在 Chrome 和 Safari 中测试过。
【解决方案3】:

let text = 'hello world';


let Allmeta = document.querySelectorAll('meta');

Allmeta.forEach((meta) => {
    if (meta.getAttribute('name') == 'description' || meta.getAttribute('itemprop') == 'description' || meta.getAttribute('property') == 'og:description') {
        meta.setAttribute('content',text)
    }
});

【讨论】:

  • 这个我试过了,没用。
猜你喜欢
  • 1970-01-01
  • 2014-08-10
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
  • 2016-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多