javascript 从文档正文中注入元标记?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12823059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:11:52  来源:igfitidea点击:

Inject a meta tag from a document's body?

javascriptjqueryhtmlmeta-tags

提问by Steve

I need to add a meta tag (specfically, <meta name="apple-itunes-app" content="app-id=xxxxx">) to a certain page, but the way our templates are set up, it's not possible for me to edit the code for the HEAD tag directly (for corporate, not technical, reasons).

我需要向<meta name="apple-itunes-app" content="app-id=xxxxx">某个页面添加一个元标记(特别是),但是我们的模板的设置方式,我无法直接编辑 HEAD 标记的代码(出于公司原因,而不是技术原因)。

Therefore, is there a way using JQuery within the BODY tag to add this meta tag?

因此,有没有办法在 BODY 标签中使用 JQuery 来添加这个元标签?

回答by Oscar Jara

Maybe you can try this:

也许你可以试试这个:

jQuery:

jQuery:

$('head').append('<meta name="apple-itunes-app" content="app-id=xxxxx">');

Javascript:

Javascript:

document.getElementsByTagName('head')[0].appendChild('<meta name="apple-itunes-app" content="app-id=xxxxx">');

回答by Denys Séguret

You can add the meta tag but as they're used before the body is even parsed, it's useless.

您可以添加元标记,但由于它们在解析正文之前就已使用,因此无用。

回答by Patrick Neeteson

$('head').append(""); << doesn't work, I even saw this in document.ready, like dystroy says: you need the tag before the body is even parsed....

$('head').append(""); << 不起作用,我什至在 document.ready 中看到了这个,就像dystroy 说的:在解析正文之前你需要标签......

For me, this did the job:

对我来说,这完成了工作:

  1. Put this in the head section, it will detect and write the meta before the body is parsed. If you don't have any conditions, just paste the html in the head section:
  1. 把它放在 head 部分,它会在解析 body 之前检测并写入元数据。如果没有条件,直接在head部分粘贴html即可:
<script type="text/javascript">
     var isiPad = navigator.userAgent.match(/iPad/i) != null;
        if(isiPad === false){
          document.write('<meta name="apple-itunes-app" content="app-id={xxxxx}">');
        }
</script>
<script type="text/javascript">
     var isiPad = navigator.userAgent.match(/iPad/i) != null;
        if(isiPad === false){
          document.write('<meta name="apple-itunes-app" content="app-id={xxxxx}">');
        }
</script>