<!DOCTYPE html>
<title>Test</title>
<meta name="description" content="this is old">
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'></script>
<button>Change description</button>
<script type='text/javascript'>
$('button').on('click', function() {
// Just replacing the value of the 'content' attribute will not work.
$('meta[name=description]').remove();
$('head').append( '<meta name="description" content="this is new">' );
});
</script>
<a href="#" onClick="changeTags(); return false;">Change Meta Tags</a>
使用 jQuery 的函数更改标记
function changeTags(){
$("#mtlink").attr("content","http://albup.com");
$("#mtdesc").attr("content","music all the time");
$("#mtkwrds").attr("content","mp3, download music, ");
}
var metaTag = document.getElementsByTagName('meta');
for (var i=0; i < metaTag.length; i++) {
if (metaTag[i].getAttribute("http-equiv")=='refresh')
metaTag[i].content = '666';
if (metaTag[i].getAttribute("name")=='Keywords')
metaTag[i].content = 'js, solver';
}
使用 Javascript 来更改页面的 meta 标记是完全有可能的。以下是仅使用 Javascript 的方法:
document.getElementsByTagName('meta')["keywords"].content = "My new page keywords!!";
document.getElementsByTagName('meta')["description"].content = "My new page description!!";
document.title = "My new Document Title!!";
var _desc = 'Out description';
var meta = document.createElement('meta');
meta.setAttribute('name', 'description');
meta.setAttribute('content', _desc);
document.getElementsByTagName('head')[0].appendChild(meta);
var description=document.getElementsByTagName('h4')[0].innerHTML;
var link = document.createElement('meta');
link.setAttribute('name', 'description');
link.content = description;
document.getElementsByTagName('head')[0].appendChild(link);
var htwo=document.getElementsByTagName('h2');
var hthree=document.getElementsByTagName('h3');
var ls=[];
for(var i=0;i<hthree.length;i++){ls.push(htwo[i].innerHTML);}
for(var i=0;i<hthree.length;i++){ls.push(hthree[i].innerHTML);}
var keyword=ls.toString()
;
var keyw = document.createElement('meta');
keyw.setAttribute('name', 'keywords');
keyw.content = keyword;
document.getElementsByTagName('head')[0].appendChild(keyw);
在我的例子中,我编写了这段代码,所有的 meta 标签都工作得很好,但是我们看不到实际的 meta 标签,它会隐藏在某个地方。