使用jQuery设置元标记值时遇到问题 [英] Having trouble using jQuery to set meta tag values

查看:87
本文介绍了使用jQuery设置元标记值时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
可以使用javascript来更改页面的元标记?

Possible Duplicate:
Is it possible to use javascript to change the meta-tags of the page?

我正在尝试使用jQuery设置元标记(请不要回答这是没有道理的,因为搜索引擎等等……我正在加载调用检查这些值的第三方Javascript函数,例如Tweetmeme和Facebook).

I'm trying to set meta tags using jQuery (please don't reply that this doesn't make sense since search engines blah-blah-blah... I am loading invoking 3rd party Javascript functions that examine these vales, such as Tweetmeme and Facebook).

如果我使用:

 $('meta[name=some-name]').attr('content', 'some value');

设置现有元标记的值确实有效,但是如果不存在这样的命名标记,则不会创建元标记.

it does work to set the value of an existing meta tag, but does not create a meta tag if such a named one does not exist.

如果您对此有见识或经验,请回复...

If you have insight or experience with this, please reply...

推荐答案

您可以执行此操作,而不是最干净的操作,但是您尝试执行的操作很奇怪,因此没有一个很好的方法来处理它:

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

其中的条件表达式检查.length,如果找不到则为0或false,如果是这种情况,我们创建元素并将其附加到头部(无论是添加还是最初找到的元素),mt现在已设置为具有该名称的<meta>,您可以设置属性.

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.

这篇关于使用jQuery设置元标记值时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆