尝试动态设置MetaTag

发布于 2024-09-17 08:22:10 字数 664 浏览 4 评论 0原文

我正在尝试动态地将元标记设置到文档的头部。这是我需要通过代码添加的移动设备特定元标记。我在这里找到了这个解决方案:

使用 jQuery 设置元标记时遇到问题value

但它似乎不起作用,我做错了什么?

function setOrCreateMetaTag(metaName, name, value) {
    var t = 'meta['+metaName+'='+name+']';
    var mt = $(t);
    if (mt.length === 0) {
        t = '<meta '+metaName+'="'+name+'" />';
        mt = $(t).appendTo('head');
    }
    mt.attr('content', value);
}

setOrCreateMetaTag(name, viewport, 'width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0');

i'm trying to dynamically set a metatag to the head of my document. This is a mobile device specific metatag that I need to add through code. I found this solution here:

Having trouble using jQuery to set meta tag values

but it doesnt seem to work, what am I doing wrong?

function setOrCreateMetaTag(metaName, name, value) {
    var t = 'meta['+metaName+'='+name+']';
    var mt = $(t);
    if (mt.length === 0) {
        t = '<meta '+metaName+'="'+name+'" />';
        mt = $(t).appendTo('head');
    }
    mt.attr('content', value);
}

setOrCreateMetaTag(name, viewport, 'width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0');

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

葵雨 2024-09-24 08:22:12

有两件事。首先确保您包含 jQuery,因为 $()​​ 是一个 jQuery 方法。这意味着包括类似的内容:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>    

第二,我认为您并不是真的想传递变量名称和视口。相反,您应该传递如下字符串:

setOrCreateMetaTag('name', 'viewport', 'width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0');

Two things. First make sure you are including jQuery, since the $() is a jQuery method. This means including something like:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>    

The second, I don't think you really meant to pass variables name and viewport. Rather, you should pass the strings like:

setOrCreateMetaTag('name', 'viewport', 'width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0');
红玫瑰 2024-09-24 08:22:12

似乎您需要在名称和视口周围加上引号,除非这些是在其他地方设置的变量:

setOrCreateMetaTag('name', 'viewport', 'width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0');

It seems like you would need quotes around name and viewport, unless these are variables set somewhere else:

setOrCreateMetaTag('name', 'viewport', 'width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文