Trying to set MetaTag dynamically

青春壹個敷衍的年華 提交于 2019-12-06 06:58:02

问题


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');

回答1:


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');



回答2:


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');


来源:https://stackoverflow.com/questions/3597768/trying-to-set-metatag-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!