将元数据附加到URL

时间:2014-07-22 22:05:03

标签: javascript meta-tags

我有三个元变量:Concept,DocType和Path,我想添加到我的网址,以便我在浏览器中看到类似" http://www.mywebsite.com/page.html?concept=var1&doctype=var2&path=var3

的内容

现在我的页面上有以下代码,但我对JS很新,不确定这是否正确:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<meta name="concept" content="product"  />
<meta name="docType" content="template"  />
<meta name="Path" content="offer"  />

<script>
function refresh() {
  var concept = document.querySelector('meta[name="concept"]');
  var doctype = document.querySelector('meta[name="docType"]');
  var path = document.querySelector('meta[name="Path"]');

  this.document.location.href = "?concept=" + concept.content + "&doctype=" + doctype.content + "&path=" + Path.content;

}
</script>

</head>

<body>
Line of text
<script>
    if (location.search.indexOf("concept") !== -1) refresh();
</script>
</body>

</html>

这给了我以下错误,我的网址没有变化:

回流焊:0.1ms 回流:0.11ms 回流:0.14ms 1406128139877 Services.HealthReport.HealthReporter警告未找到首选项数据。

1 个答案:

答案 0 :(得分:0)

使用querySelector代替getElementByName,而不是concept.value,请使用concept.content。所以你的代码看起来像这样:

<meta name="concept" content="product"  />
<meta name="docType" content="template"  />
<meta name="Path" content="offer"  />

<script>
function refresh() {
  var concept = document.querySelector('meta[name="concept"]');
  var doctype = document.querySelector('meta[name="docType"]');
  var path = document.querySelector('meta[name="Path"]');

  document.location.href = "?concept=" + concept.content + "&doctype=" + doctype.content + "&iapath=" + path.content;

}
</script>

此外,iapath.content是错误,请使用path.content,这是您的变量名称。

此外,您必须在某处调用方法refresh;否则它将无法运行:

<body>
Line of text
<script>
    if (location.search.indexOf("concept") === -1) refresh();
</script>
</body>

这段(静态)html在我可以访问的所有浏览器(chrome,firefox,IE ...)上完全在我的本地服务器上运行:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="concept" content="product"  />
    <meta name="docType" content="template"  />
    <meta name="Path" content="offer"  />
    <title>Test</title>
    <script>
    function refresh() {
        var concept = document.querySelector('meta[name="concept"]');
        var doctype = document.querySelector('meta[name="docType"]');
        var path = document.querySelector('meta[name="Path"]');

        document.location.href = "?concept=" + concept.content + "&doctype=" + doctype.content + "&iapath=" + path.content;

    }
    </script>
</head>
<body>
Line of text
<script>
    if (location.search.indexOf("concept") === -1) refresh();
</script>
</body>
</html>