Having trouble using jQuery to set meta tag values [duplicate]

耗尽温柔 提交于 2019-11-28 07:41:06

You can do this, not the cleanest, but what you're trying to do is pretty odd so there's not a great way to handle it:

var mt = $('meta[name=some-name]');
mt = mt.length ? mt : $('<meta name="some-name" />').appendTo('head');
mt.attr('content', 'some value');

The conditional expression in there checks .length, which is 0 or false if not found, if that's the case we create the element and append it to the head, whether it was added or originally found, mt is set to the <meta> with that name now, and you can set the attribute.

Leveraging Nick's code, I made a function to do the meta tag setting, creating if necessary. Should this be of use to anyone...

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

The metaName most often might be assumed to be "name" but I am also having to set "property" as well, so made the function handle a meta meta-name.

I was just experimenting with this a bit on iOS. It turned out that it was possible to dynamically set a meta tag to prevent zooming on iOS like so:

$('<meta>', {
 name: 'viewport',
 content: 'width=device-width, minimum-scale=1, maximum-scale=1'
}).appendTo('head');

Removing it however, didn't re-enable zooming:

$('meta[name=viewport]').remove();

But overwriting the meta tag:

$('meta[name=viewport]').attr(
 'content',
 'width=980, minimum-scale=0.25, maximum-scale=1.6'
);

with its default values did.

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