动态改变meta/title标签,根据页面情况用js

Dynamically change the meta/title tag, depending on the page with js

我有文档的结构:

<?
    include('head.php');
    include('header.php');
    include('index_content.php');
    include('footer.php');
    include('form.php');
    include('js.php');
?>

当我创建一个新页面时,我使用这个框架并且只改变页面内容。但对于 SEO 优化,还需要更改标题和元标记。是否可以根据页面使用 JavaScript 动态更改此设置。还是不洗澡写这样的东西比较好:

<?
    include('head.php'); //beginning of the <head> tag
?>
    <title>Some title</title>
    <meta name="description" content="some description">
    <meta name="keywords" content="some keywords">
<?
    include('header.php'); - //end of </head> tag
    include('index_content.php');
    include('footer.php');
    include('form.php');
    include('js.php');
?>

您可以直接将php变量获取到meta标签中,如下所示。

<?
    include('head.php'); //beginning of the <head> tag
?>
    <title>Some title</title>
    <meta name="description" content="<?php echo $DESCRIPTION;?>">>
    <meta name="keywords" content="<?php echo $KEYWORDS;?>">>
<?
    include('header.php'); - //end of </head> tag
    include('index_content.php');
    include('footer.php');
    include('form.php');
    include('js.php');
?>

更新

如果您使用 jquery,这可能有效

$("meta[name='description']").attr("content","<?php echo $DESCRIPTION;?>");